node:http
require('http') module · Added in vES5 · Updated March 13, 2026 · Node.js Modules The node:http module provides HTTP server and client functionality in Node.js. It’s the foundational module for building web servers and making HTTP requests. This module is built on top of Node.js’s event-driven architecture and uses streams for efficient data handling.
Common Usage
Creating a Simple HTTP Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Making HTTP GET Requests
const http = require('http');
const req = http.get('http://example.com', (res) => {
console.log(`STATUS: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`DATA: ${chunk}`);
});
res.on('end', () => {
console.log('Response complete');
});
});
req.on('error', (err) => {
console.error(`Error: ${err.message}`);
});
Making HTTP POST Requests
const http = require('http');
const data = JSON.stringify({ name: 'John', age: 30 });
const options = {
hostname: 'example.com',
port: 80,
path: '/api/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
};
const req = http.request(options, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
console.log('Response:', body);
});
});
req.write(data);
req.end();
Key Classes and Methods
http.createServer()
Creates an HTTP server instance. The request listener receives http.IncomingMessage (req) and http.ServerResponse (res) objects.
const server = http.createServer((req, res) => {
// Handle request
});
http.request()
Makes an outgoing HTTP request. Returns a http.ClientRequest instance.
const req = http.request(options, (res) => {
// Handle response
});
req.end();
http.get()
A convenience method for making GET requests. Shorthand for http.request() with method: 'GET'.
http.get('http://example.com', (res) => {
// Handle response
});
Request and Response Objects
IncomingMessage (req)
The IncomingMessage object represents the HTTP request. It inherits from stream.Readable.
Key Properties:
req.method— HTTP method (GET, POST, etc.)req.url— Request URLreq.headers— Request headers objectreq.httpVersion— HTTP version
Key Events:
data— Emitted when a chunk of data is receivedend— Emitted when the entire message is receivederror— Emitted on errors
ServerResponse (res)
The ServerResponse object represents the HTTP response. It inherits from stream.Writable.
Key Methods:
res.writeHead(statusCode, headers)— Write response headersres.write(chunk)— Write response bodyres.end()— Signal response completeres.setHeader(name, value)— Set a response headerres.getHeader(name)— Get a response headerres.removeHeader(name)— Remove a response header
Examples
Routing Based on URL
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home Page</h1>');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>About Page</h1>');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000);
Handling POST Data
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
console.log('Received:', body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: body }));
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method not allowed');
}
});
server.listen(3000);
JSON REST API
const http = require('http');
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const server = http.createServer((req, res) => {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Content-Type', 'application/json');
if (req.url === '/api/users' && req.method === 'GET') {
res.end(JSON.stringify(users));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not found' }));
}
});
server.listen(3000);
Important Notes
- The
httpmodule is a low-level module. For production applications, consider using frameworks like Express.js or Fastify. - The
httpmodule does not support HTTPS. Use thehttpsmodule for secure connections. - Always handle errors on both server and client requests to prevent unhandled exceptions.
See Also
- Https::Request — HTTPS server and client
- URL::parse — URL parsing and manipulation