L6. 🧭 Node.js – Basic Routing Example

// ROUTING IN NODE JS 🔀
// If the user hits any URL, that content should be displayed

console.log("Routing in Node.js");

import http from 'http'; // use http module to create server

// Create server 🔧
const server = http.createServer((req, res) => {
    // Log all the details of request 📥
    console.log(req);

    // Log only the requested URL 🌐
    console.log(req.url);

    // Simple Routing Logic 🛣️
    if (req.url === '/home') {
        res.end('<h1>You are requested for home page</h1>');
    }
    else if (req.url === '/contact') {
        res.end('<h1>You are requested for contact page</h1>');
    }
    else {
        res.end('<h1>Invalid route</h1>');
    }
});

// Run server on port 1000 🚪
const port = 1000;
server.listen(port, () => console.log(`Server is running on port ${port}`));

✨ Explanation

  • We use req.url to check what URL the user is visiting (like /home or /contact).

  • Based on the route, we send different responses using res.end().

  • If the user enters an unknown route, we show an “Invalid route” message.

  • This is how simple routing works without any external libraries like Express.

0
Subscribe to my newsletter

Read articles from Sahana S Acharya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahana S Acharya
Sahana S Acharya