Open In App

Creating Your Own Node HTTP Request Router

Last Updated : 04 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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?

The HTTP request router is the component in the NodeJS that directs the incoming HTTP requests to the specific endpoints or handlers that are based on the predefined rules. This also enables the mapping of URLs to corresponding functions or the resources for performing the tasks. The routing is important for implementing the structured handling of different client requests to the web server.

Approach to create Node HTTP Request Router:

  • In the above example, we have created the Node HTTP request router, whereas in the app.js file, we have set up the HTTP server.
  • In the router.js all the routes and handlers are defined.
  • When the client performs the request, the server parses the URL and performs routing to the router.js where the matching of routes is done and a response is given to the client.

Steps to create own Node HTTP Request Router

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now create the below Project Structure of our project which includes the file as app.js and router.js.

Project Structure:

Example: Use the below app.js and router.js code to create our own node HTTP request router.

Javascript




//app.js
const http = require('http');
const url = require('url');
const router = require('./router');
// creating an HTTP server
const server = http.createServer((req, res) => {
    // parsing the URL to extract the pathname
    const urlParse = url.parse(req.url, true);
    const pathname = urlParse.pathname;
    // routing the request using the router module
    router.route(pathname, req, res);
});
// server to listen on port 3000
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});


Javascript




//router.js
//defining routes
const routes = {
    '/': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Welcome to GeeksforGeeks');
    },
    '/about': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(`GeeksforGeeks is a leading platform that provides
      computer science resources and coding challenges for programmers
      and technology enthusiasts, along with interview and
      exam preparations for upcoming aspirants.`);
    },
    '/contact': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(`A-143, 9th Floor, Sovereign Corporate Tower,
      Sector-136, Noida, Uttar Pradesh - 201305 `);
    },
};
// function to handle routing
function route(pathname, req, res) {
    if (typeof routes[pathname] === 'function') {
        // if route exists, call its handler function
        routes[pathname](req, res);
    } else {
        // if route doesn't exist, return a 404 Not Found response
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
    }
}
// exporting the route function for use in app.js
module.exports = {
    route,
};


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads