Nearby lessons
13 of 21🛣️ Routing in Node JS | Serve HTML Pages
📌 What is Routing?
Routing is the mechanism by which requests (specified by a URL and HTTP method) are directed to the code that handles them.
We can serve HTML pages dynamically using Node.js by checking the URL in the request and sending the corresponding HTML file.
💻 routing.js - Node.js Server for Routing
Node.js Environment
RUNTIME ACTIVE
const http = require('http'); const fs = require('fs'); http.createServer(function (req, res) { if (req.url === '/') { res.write('<h1>This is Home page Codings Points tutorial</h1>'); res.end(); } else if (req.url === '/about') { fs.readFile('./about.html', (err, data) => { if (err) throw err; res.write(data); res.end(); }); } else if (req.url === '/contact') { fs.readFile('./contact.html', (err, data) => { if (err) throw err; res.write(data); res.end(); }); } else { res.write('<h1>404 Page Not Found..</h1>'); res.end(); } }).listen(3000, "localhost", () => { console.log("Server Running At http://localhost:3000"); });
Terminal Output
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3
Keep Going!Path Module in Node.js