Horje
Creating Your Own Node HTTP Request Router

In Node, if we want to build our own custom HTTP request router then we can create it by handling the incoming requests and directing them to the specific endpoints. Using this routing process, allows us to define the different actions or responses that are based on the requested URLs. In this article, we will create our own node HTTP request router.

Prerequisites:

What is an HTTP Request Router?

An HTTP request router is a system or component within a web server or framework that analyzes incoming HTTP requests. It have a capability to match an endpoint with a defined set of routes in the program and forward them to the corresponding handler or controller.

Approach to create Node HTTP Request Router:

  • In this example first we will create a folder name server.js or app.js.
  • Then we require the ‘http’ module for that we do not need any npm installation because it is a node.js built-in module.
  • After that we setup our node server using “createServer” method.
  • Then we define our routes or end points using URL module.

Example : Below is the code example of how to creating Our own Node HTTP Request Router

JavaScript
const http = require('http');
const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end("Home page");
    }
    else if (req.url === '/about') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('About us page');
    } else {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end('<h1>404 Not Found</h1>');
    }
});

server.listen(3000, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log(`Server is started at port no 3000`);
    }
});

Output:




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to generate webpages using CGI scripts? How to generate webpages using CGI scripts?
How to Install Matplotlib on Anaconda? How to Install Matplotlib on Anaconda?
List of Coding languages supported by ChatGPT List of Coding languages supported by ChatGPT
How To Enable or Disable CGI Scripts in Apache? How To Enable or Disable CGI Scripts in Apache?
Role of Postman in the API development lifecycle. Role of Postman in the API development lifecycle.

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12