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.urlto check what URL the user is visiting (like/homeor/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.