Skip to main content
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’

  • request
  • response
Emitted each time there is a request.
server.on('request', (req, res) => {
  console.log('Request received:', req.url);
});

Event: ‘connection’

  • socket
Emitted when a new TCP stream is established.

Event: ‘close’

Emitted when the server closes.

Event: ‘clientError’

  • exception
  • socket
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])

  • port
  • host
  • callback
Start the HTTP server listening for connections.

server.close([callback])

  • 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.

server.maxHeadersCount

  • Type: Default: 2000
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

message.headers

  • Type:
The request/response headers object.
console.log(request.headers);
// {
//   'content-type': 'text/plain',
//   'host': 'example.com'
// }

message.method

  • Type:
The request method (only valid for requests received by server).
console.log(request.method); // 'GET', 'POST', etc.

message.url

  • Type:
Request URL string (only valid for requests received by server).
console.log(request.url); // '/path?query=value'

message.statusCode

  • Type:
The 3-digit HTTP response status code (only valid for response from ClientRequest).

message.statusMessage

  • Type:
The HTTP response status message (only valid for response from ClientRequest).

Methods

message.setTimeout(msecs[, callback])

  • 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

response.writeHead(statusCode[, statusMessage][, headers])

  • 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])

  • data
  • encoding
  • callback
Signals that all response headers and body have been sent.
response.end('Done!');

response.setHeader(name, value)

  • name
  • value
Sets a single header value.
response.setHeader('Content-Type', 'application/json');

response.getHeader(name)

  • name
  • Returns:
Reads out a header that’s already been queued but not sent.

response.removeHeader(name)

  • name
Removes a header that’s queued for implicit sending.

Properties

response.statusCode

  • Type: Default: 200
The HTTP status code to send.
response.statusCode = 404;

response.statusMessage

  • Type:
The HTTP status message to send.

Class: http.ClientRequest

This object is created internally and returned from http.request().

Events

Event: ‘response’

  • response
Emitted when a response is received to this request.
request.on('response', (response) => {
  console.log('STATUS:', response.statusCode);
});

Event: ‘socket’

  • socket
Emitted after a socket is assigned to this request.

Methods

request.write(chunk[, encoding][, callback])

  • chunk
  • encoding
  • callback
Sends a chunk of the request body.

request.end([data[, encoding]][, callback])

  • data
  • encoding
  • callback
Finishes sending the request.
const postData = JSON.stringify({ key: 'value' });
request.write(postData);
request.end();

request.setHeader(name, value)

  • name
  • value
Sets a single header value for the request.

request.setTimeout(timeout[, callback])

  • 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');
  }
});

Working with Headers

Request Headers

server.on('request', (req, res) => {
  console.log(req.headers['user-agent']);
  console.log(req.headers['content-type']);
  console.log(req.headers.host);
});

Response Headers

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();