Skip to content

Node.js http API

Node.js http module for building HTTP servers and issuing HTTP clients requests.

1 class · 4 methods

http

4 methods

Server and client utilities from the http module.

http.createServer(requestListener?) -> http.Server

Returns a new HTTP server that invokes the listener for each request.

Parameters

NameTypeDescription
requestListener(req, res) => voidFunction called with IncomingMessage and ServerResponse.

Returns

http.Server

Example

nodejs
import http from 'node:http';
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'text/plain' });
  res.end('hello');
});
http.request(options, callback?) -> http.ClientRequest

Initiates an HTTP request and returns the ClientRequest; emit 'response' or pass a callback.

Parameters

NameTypeDescription
optionsobject | string | URL{ method, hostname, port, path, headers } or URL.
callback(res) => voidOptional response handler.

Returns

http.ClientRequest

Example

nodejs
import http from 'node:http';
const req = http.request({ hostname: 'localhost', port: 3000, path: '/health', method: 'GET' }, (res) => {
  console.log(res.statusCode);
});
req.end();
server.listen(port, hostname?, callback?) -> server

Starts listening for connections on the given port and optional hostname.

Parameters

NameTypeDescription
portnumberTCP port; 0 picks a random free port.
hostnamestringOptional bind address; defaults to all interfaces.
callback() => voidCalled once listening has started.

Returns

http.Server

Example

nodejs
server.listen(3000, '127.0.0.1', () => {
  console.log('listening on 3000');
});
http.get(options, callback?) -> http.ClientRequest

Convenience method for GET requests; auto-calls req.end().

Parameters

NameTypeDescription
optionsobject | string | URLRequest target.
callback(res) => voidOptional response handler.

Returns

http.ClientRequest

Example

nodejs
http.get('http://localhost:3000/health', (res) => {
  res.on('data', (c) => process.stdout.write(c));
});