Here’s a simple example of how you can dynamically route a server in pure vanilla NodeJS without any packages :
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.url);
if (req.url === "/about") {
res.end("This is the About page");
} else if (req.url === "/contacts") {
res.end("This is the contacts page");
} else {
res.end("Hello from the server");
}
});
server.listen(8000, "localhost", () => {
console.log("Server started successfully!");
});
Steps :
- http module activated by ‘requiring http’
- Server started on port 8000 (localhost:8000/)
- Activated the server by using the request(req), response(res) cycle
- ‘/about’ and ‘/contacts’ the routes which shows the messages