Routing Response

Routing in Node.js refers to determining the action to take for a specific request, based on the URL of the request.

Here's an example of how you could implement routing using an if...else statement.


const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  const url = req.url;
  if (url === '/'){
    res.end(
        "Welcome to nodejs guide."
    )
  }
  if (url === '/about'){
    res.end(
        "Sab janna h isko."
    )
  }

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When a client makes a request to the home page ('/'), the first route handler will be executed, and the response will be "Welcome to nodejs guide.". Similarly, when a client makes a request to the about page ('/about'), the second route handler will be executed, and the response will be "Sab janna h isko."

Last updated