Creating a Basic HTTP Server
Node.js has a built-in http module that lets you create web servers without any external packages. The http.createServer() method creates a server that listens for incoming requests and sends responses.
Every HTTP request triggers a callback function with two objects: req (the incoming request) and res (the response you send back). This is the foundation for all Node.js web applications.
const http = require('http');
const server = http.createServer((req, res) => {
// Set the response headers
res.writeHead(200, { 'Content-Type': 'text/html' });
// Send the response body
res.end('<h1>Hello from Node.js Server!</h1>');
});
// Start listening on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
// Visit http://localhost:3000 in your browser - http.createServer() — Creates an HTTP server with a request handler
- req — The incoming request object (URL, method, headers, body)
- res — The response object (set headers, status code, send data)
- res.writeHead() — Set status code and response headers
- res.end() — Send the response body and finish the response
- server.listen() — Start the server on a specific port
- Always call res.end() to finish the response. If you forget, the browser will keep waiting and eventually time out.
Handling Routes and Serving HTML
You can check the request URL and method to handle different routes. This is basic routing — checking which page the user is requesting and sending the appropriate response.
While this works for simple servers, building a full application with manual routing becomes complex quickly. That is why frameworks like Express.js exist.
const http = require('http');
const fs = require('fs').promises;
const path = require('path');
const server = http.createServer(async (req, res) => {
console.log(`${req.method} ${req.url}`);
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home Page</h1><a href="/about">About</a>');
} else if (req.url === '/about' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>About Page</h1><a href="/">Home</a>');
} else if (req.url === '/api/data' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello from API', status: 'ok' }));
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 - Page Not Found</h1>');
}
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
}); - Common HTTP status codes: 200 (OK), 201 (Created), 301 (Redirect), 400 (Bad Request), 404 (Not Found), 500 (Server Error).
