0
0
Node.jsframework~5 mins

Routing requests manually in Node.js

Choose your learning style9 modes available
Introduction

Routing requests manually means deciding what to do based on the web address a user visits. It helps your server send the right response for each request.

You want to handle different web pages or API endpoints without using extra libraries.
You are learning how web servers work by controlling requests step-by-step.
You need a simple server that responds differently based on the URL path.
You want to customize how your server reacts to specific URLs or HTTP methods.
Syntax
Node.js
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    // handle root path
  } else if (req.url === '/about') {
    // handle about page
  } else {
    // handle 404 not found
  }
});

server.listen(3000);

Use req.url to check the requested path.

Use res.writeHead() and res.end() to send responses.

Examples
Responds with 'Home page' when the root URL is requested.
Node.js
if (req.url === '/') {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Home page');
}
Responds with 'About us' when the '/about' URL is requested.
Node.js
if (req.url === '/about') {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('About us');
}
Sends a 404 error message for unknown URLs.
Node.js
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Page not found');
Sample Program

This server listens on port 3000. It sends a welcome message for the root URL, contact info for '/contact', and a 404 message for other URLs.

Node.js
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Welcome to the Home page!');
  } else if (req.url === '/contact') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Contact us at contact@example.com');
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('404: Page not found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
OutputSuccess
Important Notes

Check req.method if you want to handle GET, POST, or other HTTP methods differently.

Manual routing is simple but can get hard to manage for many routes; frameworks help with this.

Summary

Manual routing uses req.url to decide how to respond.

Use res.writeHead() and res.end() to send responses.

This method is good for learning or small servers without extra tools.