Skip to main content

Command Palette

Search for a command to run...

L6. 🧭 Node.js – Basic Routing Example

Published
β€’1 min readβ€’View as Markdown
// 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.

More from this blog

N

Nodejs

12 posts