Basic routing using HTTP Node Js

 


const http = require('http');

let  index = (req, res) => {
 res.writeHead(200);
 res.end('Hello, World!');
}

http.createServer((req, res) => {
    if (req.url === '/') //If user given route is /
    {
        return index(req, res);
    }
    else ////If user given route is not /
    {
        res.writeHead(404);
        res.end(http.STATUS_CODES[404]);
    }

}).listen(2000);

OUTPUT:- 


 check if (request.url === '/'), and then call a function that responds with a new file.

If we continue to define our "routes" like this, though, we will end up with one massive callback function, and we don't want a giant mess like that, so let's see if we can clean this up. 


const http = require("http");

var routes = {
  "/": (req, res) => {
    res.writeHead(200);
    res.end("Hello, World!");
  },
  "/name": (req, res) => {
    res.writeHead(200);
    res.end('My name is Demo');
  },
};

http.createServer(function (req, res) {
    if (req.url in routes) {
      return routes[req.url](req, res);
    }
    res.writeHead(404);
    res.end(http.STATUS_CODES[404]);
  }).listen(2000);


OUTPUT:- 




Comments