http is Node.js's built-in module that lets it act as a web server, accepting requests and sending back responses. Before you reach for Express.js, this module is the best foundation for understanding the HTTP request/response flow.
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
if (req.url === '/') {
res.statusCode = 200;
res.end('<h1>Home Page</h1><p>Welcome to Node.js.</p>');
} else if (req.url === '/about') {
res.statusCode = 200;
res.end('<h1>About Page</h1><p>This page is served by Node.js.</p>');
} else {
res.statusCode = 404;
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(5000, () => {
console.log('Server is listening on http://localhost:5000');
});req.url shows the path the user requested. / returns the home page, and /about returns the about page. If nothing matches, it returns a 404 status code with a not-found message.
Server is listening on http://localhost:5000 Browser: http://localhost:5000/about About PageInfo
Returning the correct status code matters a lot for API/web server quality. Use 200 for success, 201 for created, 404 for not found, and 500 for server errors, and so on.