How to handle NodeJS Routing and HTTP Requests.

const http = require("http");
const server = http.createServer((req, res)=>{
    // console.log(req.url);
    if(req.url == "/"){
        res.end("hello, i'm shreyash");
    }else if(req.url == "/about"){

        res.end("hello this is about page");
    }
});
server.listen(8000,"127.0.0.1",()=>{
    console.log("listening to the port n0. 8000")
})
Go to browser and type localhost:8000 there output will be show "hello , i'm shreyash" and go to localhost:8000/about then will be show "hello this is about page " this is nodeJS routing and i used nodemon npm package to reload automatically.



const http = require("http");
const server = http.createServer((req, res)=>{
    // console.log(req.url);
    if(req.url == "/"){
        res.end("hello, i'm shreyash");
    }else if(req.url == "/about"){
        res.end("hello this is about page");
    }else if(req.url == "/contact"){
        res.end("hello this is contact page");
    }else if(req.url == "/blog"){
        res.end("hello this is blog page");
    }else{
        res.writeHead(404);
        res.end("404 error, page does not exit");
    }
});
server.listen(8000,"127.0.0.1",()=>{
    console.log("listening to the port n0. 8000")
})
Output



const http = require("http");
const server = http.createServer((req, res)=>{
    // console.log(req.url);
    if(req.url == "/"){
        res.end("hello, i'm shreyash");
    }else if(req.url == "/about"){
        res.end("hello this is about page");
    }else if(req.url == "/contact"){
        res.end("hello this is contact page");
    }else if(req.url == "/blog"){
        res.end("hello this is blog page");
    }else{
        res.writeHead(404,{"content-type":"text/html"});
        res.end("<h1>404 error, page does not exit</h1>");
    }
});
server.listen(8000,"127.0.0.1",()=>{
    console.log("listening to the port n0. 8000")
})