Documentation Index
Fetch the complete documentation index at: https://mintlify.com/nodejs/node/llms.txt
Use this file to discover all available pages before exploring further.
The node:http module provides HTTP server and client functionality.
Import
import http from 'node:http';
// or
const http = require('node:http');
Class: http.Server
This class is used to create an HTTP server.
Creating a Server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Events
Event: ‘request’
Emitted each time there is a request.
server.on('request', (req, res) => {
console.log('Request received:', req.url);
});
Event: ‘connection’
Emitted when a new TCP stream is established.
Event: ‘close’
Emitted when the server closes.
Event: ‘clientError’
Emitted when a client connection emits an error.
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
Methods
server.listen([port][, host][, callback])
Start the HTTP server listening for connections.
server.close([callback])
Stops the server from accepting new connections.
server.setTimeout([msecs][, callback])
msecs Default: 120000 (2 minutes)
callback
Sets the timeout value for sockets.
Properties
server.timeout
- Type: Default: 0 (no timeout)
The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.keepAliveTimeout
- Type: Default:
5000 (5 seconds)
The number of milliseconds of inactivity a server needs to wait for additional incoming data.
Limits maximum incoming headers count.
Class: http.IncomingMessage
An IncomingMessage object is created by http.Server or http.ClientRequest and represents the request (on server) or response (on client).
Properties
The request/response headers object.
console.log(request.headers);
// {
// 'content-type': 'text/plain',
// 'host': 'example.com'
// }
message.method
The request method (only valid for requests received by server).
console.log(request.method); // 'GET', 'POST', etc.
message.url
Request URL string (only valid for requests received by server).
console.log(request.url); // '/path?query=value'
message.statusCode
The 3-digit HTTP response status code (only valid for response from ClientRequest).
message.statusMessage
The HTTP response status message (only valid for response from ClientRequest).
Methods
message.setTimeout(msecs[, callback])
Calls message.socket.setTimeout(msecs, callback).
Class: http.ServerResponse
This object is created internally by an HTTP server and passed as the second parameter to the 'request' event.
Methods
statusCode
statusMessage
headers
Sends a response header to the request.
response.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(body)
});
response.write(chunk[, encoding][, callback])
chunk
encoding
callback
- Returns:
Sends a chunk of the response body.
response.write('Hello ');
response.write('World');
response.end([data[, encoding]][, callback])
Signals that all response headers and body have been sent.
Sets a single header value.
response.setHeader('Content-Type', 'application/json');
Reads out a header that’s already been queued but not sent.
Removes a header that’s queued for implicit sending.
Properties
response.statusCode
The HTTP status code to send.
response.statusCode = 404;
response.statusMessage
The HTTP status message to send.
Class: http.ClientRequest
This object is created internally and returned from http.request().
Events
Event: ‘response’
Emitted when a response is received to this request.
request.on('response', (response) => {
console.log('STATUS:', response.statusCode);
});
Event: ‘socket’
Emitted after a socket is assigned to this request.
Methods
request.write(chunk[, encoding][, callback])
Sends a chunk of the request body.
request.end([data[, encoding]][, callback])
Finishes sending the request.
const postData = JSON.stringify({ key: 'value' });
request.write(postData);
request.end();
Sets a single header value for the request.
request.setTimeout(timeout[, callback])
Once a socket is assigned and is connected, socket.setTimeout() will be called.
HTTP Methods
http.get(url[, options][, callback])
url
options
callback
- Returns:
Convenience method for making GET requests.
http.get('http://example.com/', (res) => {
console.log('STATUS:', res.statusCode);
res.on('data', (chunk) => {
console.log('BODY:', chunk);
});
}).on('error', (e) => {
console.error('ERROR:', e.message);
});
http.request(url[, options][, callback])
url
options
method Default: 'GET'
host Default: 'localhost'
port Default: 80
path Default: '/'
headers
callback
- Returns:
Makes an HTTP request.
const options = {
hostname: 'example.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(options, (res) => {
console.log('STATUS:', res.statusCode);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log('BODY:', chunk);
});
});
req.on('error', (e) => {
console.error('Problem with request:', e.message);
});
req.write(JSON.stringify({ key: 'value' }));
req.end();
HTTP Status Codes
Common Status Codes
200 - OK
201 - Created
204 - No Content
301 - Moved Permanently
302 - Found
304 - Not Modified
400 - Bad Request
401 - Unauthorized
403 - Forbidden
404 - Not Found
500 - Internal Server Error
502 - Bad Gateway
503 - Service Unavailable
Using Status Codes
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('OK');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
}
});
server.on('request', (req, res) => {
console.log(req.headers['user-agent']);
console.log(req.headers['content-type']);
console.log(req.headers.host);
});
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Custom-Header', 'value');
res.setHeader('Set-Cookie', ['cookie1=value1', 'cookie2=value2']);
Example: Simple Web Server
import http from 'node:http';
import fs from 'node:fs';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream('index.html').pipe(res);
} else if (req.method === 'POST' && req.url === '/api/data') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: data }));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
server.listen(3000);
Example: HTTP Client
import http from 'node:http';
const options = {
hostname: 'api.example.com',
port: 80,
path: '/data',
method: 'GET',
headers: {
'Accept': 'application/json'
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', (error) => {
console.error('Error:', error);
});
req.end();