Episode 4 of 12
Requests & Responses
Dive deeper into HTTP requests and responses, handle different URLs, and serve HTML pages from your Node.js server.
Now that you can create a basic server, let's learn to handle different routes and serve dynamic content.
Routing Requests
A real server needs to respond differently based on the URL:
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
let path = './views/';
switch (req.url) {
case '/':
path += 'index.html';
res.statusCode = 200;
break;
case '/about':
path += 'about.html';
res.statusCode = 200;
break;
default:
path += '404.html';
res.statusCode = 404;
break;
}
// Read and serve the HTML file
fs.readFile(path, (err, data) => {
if (err) {
console.log(err);
res.end();
} else {
res.end(data);
}
});
});
server.listen(3000);
Status Codes
HTTP status codes tell the browser what happened:
- 200 — OK (success)
- 301 — Moved permanently (redirect)
- 404 — Not found
- 500 — Internal server error
Redirects
You can redirect users from old URLs to new ones:
case '/about-us':
res.statusCode = 301;
res.setHeader('Location', '/about');
res.end();
break;
This tells the browser: "This page has moved permanently to /about."