HTTP | Node.js v17.9.1 Documentation (original) (raw)

Source Code: lib/http.js

To use the HTTP server and client one must require('http').

The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.

HTTP message headers are represented by an object like this:

{ 'content-length': '123',
  'content-type': 'text/plain',
  'connection': 'keep-alive',
  'host': 'example.com',
  'accept': '*/*' }

Keys are lowercased. Values are not modified.

In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.

See message.headers for details on how duplicate headers are handled.

The raw headers as they were received are retained in the rawHeadersproperty, which is an array of [key, value, key2, value2, ...]. For example, the previous message header object might have a rawHeaderslist like the following:

[ 'ConTent-Length', '123456',
  'content-LENGTH', '123',
  'content-type', 'text/plain',
  'CONNECTION', 'keep-alive',
  'Host', 'example.com',
  'accepT', '*/*' ]

Class: http.Agent#

Added in: v0.3.4

An Agent is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on thekeepAlive option.

Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed from the pool and a new connection will be made when a new HTTP request is made for that host and port. Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every request and cannot be pooled. The Agent will still make the requests to that server, but each one will occur over a new connection.

When a connection is closed by the client or the server, it is removed from the pool. Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests. (see socket.unref()).

It is good practice, to destroy() an Agent instance when it is no longer in use, because unused sockets consume OS resources.

Sockets are removed from an agent when the socket emits either a 'close' event or an 'agentRemove' event. When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done:

http.get(options, (res) => {
  // Do stuff
}).on('socket', (socket) => {
  socket.emit('agentRemove');
});

An agent may also be used for an individual request. By providing{agent: false} as an option to the http.get() or http.request()functions, a one-time use Agent with default options will be used for the client connection.

agent:false:

http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: false  // Create a new agent just for this one request
}, (res) => {
  // Do stuff with response
});

new Agent([options])#

options in socket.connect() are also supported.

The default http.globalAgent that is used by http.request() has all of these values set to their respective defaults.

To configure any of them, a custom http.Agent instance must be created.

const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);

agent.createConnection(options[, callback])#

Added in: v0.11.4

Produces a socket/stream to be used for HTTP requests.

By default, this function is the same as net.createConnection(). However, custom agents may override this method in case greater flexibility is desired.

A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function, or by passing the socket/stream to callback.

This method is guaranteed to return an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

callback has a signature of (err, stream).

agent.keepSocketAlive(socket)#

Added in: v8.1.0

Called when socket is detached from a request and could be persisted by theAgent. Default behavior is to:

socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;

This method can be overridden by a particular Agent subclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.

The socket argument can be an instance of <net.Socket>, a subclass of<stream.Duplex>.

agent.reuseSocket(socket, request)#

Added in: v8.1.0

Called when socket is attached to request after being persisted because of the keep-alive options. Default behavior is to:

socket.ref();

This method can be overridden by a particular Agent subclass.

The socket argument can be an instance of <net.Socket>, a subclass of<stream.Duplex>.

agent.destroy()#

Added in: v0.11.4

Destroy any sockets that are currently in use by the agent.

It is usually not necessary to do this. However, if using an agent with keepAlive enabled, then it is best to explicitly shut down the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them.

agent.freeSockets#

An object which contains arrays of sockets currently awaiting use by the agent when keepAlive is enabled. Do not modify.

Sockets in the freeSockets list will be automatically destroyed and removed from the array on 'timeout'.

agent.getName([options])#

Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returnshost:port:localAddress or host:port:localAddress:family. For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.

agent.maxFreeSockets#

Added in: v0.11.7

By default set to 256. For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.

agent.maxSockets#

Added in: v0.3.6

By default set to Infinity. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of agent.getName().

agent.maxTotalSockets#

Added in: v14.5.0, v12.19.0

By default set to Infinity. Determines how many concurrent sockets the agent can have open. Unlike maxSockets, this parameter applies across all origins.

agent.requests#

An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

agent.sockets#

An object which contains arrays of sockets currently in use by the agent. Do not modify.

Class: http.ClientRequest#

Added in: v0.1.17

This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value),getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when calling request.end().

To get the response, add a listener for 'response' to the request object.'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of http.IncomingMessage.

During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

If no 'response' handler is added, then the response will be entirely discarded. However, if a 'response' event handler is added, then the data from the response object must be consumed, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

For backward compatibility, res will only emit 'error' if there is an'error' listener registered.

Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

Event: 'abort'#

Added in: v1.4.1Deprecated since: v17.0.0

Stability: 0 - Deprecated. Listen for the 'close' event instead.

Emitted when the request has been aborted by the client. This event is only emitted on the first call to abort().

Event: 'connect'#

Added in: v0.7.0

Emitted each time a server responds to a request with a CONNECT method. If this event is not being listened for, clients receiving a CONNECT method will have their connections closed.

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

A client and server pair demonstrating how to listen for the 'connect' event:

const http = require('http');
const net = require('net');
const { URL } = require('url');

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                    'Proxy-agent: Node.js-Proxy\r\n' +
                    '\r\n');
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {

  // Make a request to a tunneling proxy
  const options = {
    port: 1337,
    host: '127.0.0.1',
    method: 'CONNECT',
    path: 'www.google.com:80'
  };

  const req = http.request(options);
  req.end();

  req.on('connect', (res, socket, head) => {
    console.log('got connected!');

    // Make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', (chunk) => {
      console.log(chunk.toString());
    });
    socket.on('end', () => {
      proxy.close();
    });
  });
});

Event: 'continue'#

Added in: v0.3.2

Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.

Event: 'information'#

Added in: v10.0.0

Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the HTTP version, status code, status message, key-value headers object, and array with the raw header names followed by their respective values.

const http = require('http');

const options = {
  host: '127.0.0.1',
  port: 8080,
  path: '/length_request'
};

// Make a request
const req = http.request(options);
req.end();

req.on('information', (info) => {
  console.log(`Got information prior to main response: ${info.statusCode}`);
});

101 Upgrade statuses do not fire this event due to their break from the traditional HTTP request/response chain, such as web sockets, in-place TLS upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the'upgrade' event instead.

Event: 'response'#

Added in: v0.1.0

Emitted when a response is received to this request. This event is emitted only once.

Event: 'socket'#

Added in: v0.5.3

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

Event: 'timeout'#

Added in: v0.7.8

Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be destroyed manually.

See also: request.setTimeout().

Event: 'upgrade'#

Added in: v0.1.94

Emitted each time a server responds to a request with an upgrade. If this event is not being listened for and the response status code is 101 Switching Protocols, clients receiving an upgrade header will have their connections closed.

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

A client server pair demonstrating how to listen for the 'upgrade' event.

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
server.on('upgrade', (req, socket, head) => {
  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
               'Upgrade: WebSocket\r\n' +
               'Connection: Upgrade\r\n' +
               '\r\n');

  socket.pipe(socket); // echo back
});

// Now that server is running
server.listen(1337, '127.0.0.1', () => {

  // make a request
  const options = {
    port: 1337,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };

  const req = http.request(options);
  req.end();

  req.on('upgrade', (res, socket, upgradeHead) => {
    console.log('got upgraded!');
    socket.end();
    process.exit(0);
  });
});

request.abort()#

Added in: v0.3.8Deprecated since: v14.1.0, v13.14.0

Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.

request.aborted#

The request.aborted property will be true if the request has been aborted.

request.connection#

Added in: v0.3.0Deprecated since: v13.0.0

See request.socket.

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

Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating '0\r\n\r\n'.

If data is specified, it is equivalent to callingrequest.write(data, encoding) followed by request.end(callback).

If callback is specified, it will be called when the request stream is finished.

request.destroy([error])#

Destroy the request. Optionally emit an 'error' event, and emit a 'close' event. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.

See writable.destroy() for further details.

request.destroyed#

Added in: v14.1.0, v13.14.0

Is true after request.destroy() has been called.

See writable.destroyed for further details.

request.finished#

Added in: v0.0.1Deprecated since: v13.4.0, v12.16.0

The request.finished property will be true if request.end()has been called. request.end() will automatically be called if the request was initiated via http.get().

request.flushHeaders()#

Added in: v1.6.0

Flushes the request headers.

For efficiency reasons, Node.js normally buffers the request headers untilrequest.end() is called or the first chunk of request data is written. It then tries to pack the request headers and data into a single TCP packet.

That's usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. request.flushHeaders() bypasses the optimization and kickstarts the request.

request.getHeader(name)#

Added in: v1.6.0

Reads out a header on the request. The name is case-insensitive. The type of the return value depends on the arguments provided torequest.setHeader().

request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]

request.getRawHeaderNames()#

Added in: v15.13.0, v14.17.0

Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.

request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headerNames = request.getRawHeaderNames();
// headerNames === ['Foo', 'Set-Cookie']

request.maxHeadersCount#

Limits maximum response headers count. If set to 0, no limit will be applied.

request.path#

Added in: v0.4.0

request.method#

Added in: v0.1.97

request.host#

Added in: v14.5.0, v12.19.0

request.protocol#

Added in: v14.5.0, v12.19.0

request.removeHeader(name)#

Added in: v1.6.0

Removes a header that's already defined into headers object.

request.removeHeader('Content-Type');

request.reusedSocket#

Added in: v13.0.0, v12.16.0

When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.

const http = require('http');

// Server has a 5 seconds keep-alive timeout by default
http
  .createServer((req, res) => {
    res.write('hello\n');
    res.end();
  })
  .listen(3000);

setInterval(() => {
  // Adapting a keep-alive agent
  http.get('http://localhost:3000', { agent }, (res) => {
    res.on('data', (data) => {
      // Do nothing
    });
  });
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout

By marking a request whether it reused socket or not, we can do automatic error retry base on it.

const http = require('http');
const agent = new http.Agent({ keepAlive: true });

function retriableRequest() {
  const req = http
    .get('http://localhost:3000', { agent }, (res) => {
      // ...
    })
    .on('error', (err) => {
      // Check if retry is needed
      if (req.reusedSocket && err.code === 'ECONNRESET') {
        retriableRequest();
      }
    });
}

retriableRequest();

request.setHeader(name, value)#

Added in: v1.6.0

Sets a single header value for headers object. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, request.getHeader() may return non-string values. However, the non-string values will be converted to strings for network transmission.

request.setHeader('Content-Type', 'application/json');

or

request.setHeader('Cookie', ['type=ninja', 'language=javascript']);

request.setNoDelay([noDelay])#

Added in: v0.5.9

Once a socket is assigned to this request and is connectedsocket.setNoDelay() will be called.

request.setSocketKeepAlive([enable][, initialDelay])#

Added in: v0.5.9

Once a socket is assigned to this request and is connectedsocket.setKeepAlive() will be called.

request.setTimeout(timeout[, callback])#

Once a socket is assigned to this request and is connectedsocket.setTimeout() will be called.

request.socket#

Added in: v0.3.0

Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit 'readable' events because of how the protocol parser attaches to the socket.

const http = require('http');
const options = {
  host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
  const ip = req.socket.localAddress;
  const port = req.socket.localPort;
  console.log(`Your IP address is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>i</mi><mi>p</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>y</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>s</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>c</mi><mi>e</mi><mi>p</mi><mi>o</mi><mi>r</mi><mi>t</mi><mi>i</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">{ip} and your source port is </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">i</span><span class="mord mathnormal">p</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal">yo</span><span class="mord mathnormal">u</span><span class="mord mathnormal">rso</span><span class="mord mathnormal">u</span><span class="mord mathnormal">rce</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span></span></span></span>{port}.`);
  // Consume response object
});

This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket>.

request.writableEnded#

Added in: v12.9.0

Is true after request.end() has been called. This property does not indicate whether the data has been flushed, for this userequest.writableFinished instead.

request.writableFinished#

Added in: v12.7.0

Is true if all data has been flushed to the underlying system, immediately before the 'finish' event is emitted.

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

Added in: v0.1.29

Sends a chunk of the body. This method can be called multiple times. If noContent-Length is set, data will automatically be encoded in HTTP Chunked transfer encoding, so that server knows when the data ends. TheTransfer-Encoding: chunked header is added. Calling request.end()is necessary to finish sending the request.

The encoding argument is optional and only applies when chunk is a string. Defaults to 'utf8'.

The callback argument is optional and will be called when this chunk of data is flushed, but only if the chunk is non-empty.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory.'drain' will be emitted when the buffer is free again.

When write function is called with empty string or buffer, it does nothing and waits for more input.

Class: http.Server#

Added in: v0.1.17

Event: 'checkContinue'#

Added in: v0.3.0

Emitted each time a request with an HTTP Expect: 100-continue is received. If this event is not listened for, the server will automatically respond with a 100 Continue as appropriate.

Handling this event involves calling response.writeContinue() if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.

When this event is emitted and handled, the 'request' event will not be emitted.

Event: 'checkExpectation'#

Added in: v5.5.0

Emitted each time a request with an HTTP Expect header is received, where the value is not 100-continue. If this event is not listened for, the server will automatically respond with a 417 Expectation Failed as appropriate.

When this event is emitted and handled, the 'request' event will not be emitted.

Event: 'clientError'#

If a client connection emits an 'error' event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

Default behavior is to try close the socket with a HTTP '400 Bad Request', or a HTTP '431 Request Header Fields Too Large' in the case of aHPE_HEADER_OVERFLOW error. If the socket is not writable or has already written data it is immediately destroyed.

socket is the net.Socket object that the error originated from.

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

When the 'clientError' event occurs, there is no request or responseobject, so any HTTP response sent, including response headers and payload,must be written directly to the socket object. Care must be taken to ensure the response is a properly formatted HTTP response message.

err is an instance of Error with two extra columns:

In some cases, the client has already received the response and/or the socket has already been destroyed, like in case of ECONNRESET errors. Before trying to send data to the socket, it is better to check that it is still writable.

server.on('clientError', (err, socket) => {
  if (err.code === 'ECONNRESET' || !socket.writable) {
    return;
  }

  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

Event: 'close'#

Added in: v0.1.4

Emitted when the server closes.

Event: 'connect'#

Added in: v0.7.0

Emitted each time a client requests an HTTP CONNECT method. If this event is not listened for, then clients requesting a CONNECT method will have their connections closed.

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

After this event is emitted, the request's socket will not have a 'data'event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.

Event: 'connection'#

Added in: v0.1.0

This event is emitted when a new TCP stream is established. socket is typically an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit 'readable' events because of how the protocol parser attaches to the socket. The socket can also be accessed at request.socket.

This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any Duplex stream can be passed.

If socket.setTimeout() is called here, the timeout will be replaced withserver.keepAliveTimeout when the socket has served a request (ifserver.keepAliveTimeout is non-zero).

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

Event: 'request'#

Added in: v0.1.0

Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).

Event: 'upgrade'#

Emitted each time a client requests an HTTP upgrade. Listening to this event is optional and clients cannot insist on a protocol change.

After this event is emitted, the request's socket will not have a 'data'event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.

This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.

server.close([callback])#

Added in: v0.1.90

Stops the server from accepting new connections. See net.Server.close().

server.headersTimeout#

Added in: v11.3.0, v10.14.0

Limit the amount of time the parser will wait to receive the complete HTTP headers.

In case of inactivity, the rules defined in server.timeout apply. However, that inactivity based timeout would still allow the connection to be kept open if the headers are being sent very slowly (by default, up to a byte per 2 minutes). In order to prevent this, whenever header data arrives an additional check is made that more than server.headersTimeout milliseconds has not passed since the connection was established. If the check fails, a 'timeout'event is emitted on the server object, and (by default) the socket is destroyed. See server.timeout for more information on how timeout behavior can be customized.

server.listen()#

Starts the HTTP server listening for connections. This method is identical to server.listen() from net.Server.

server.listening#

Added in: v5.7.0

server.maxHeadersCount#

Added in: v0.7.0

Limits maximum incoming headers count. If set to 0, no limit will be applied.

server.requestTimeout#

Added in: v14.11.0

Sets the timeout value in milliseconds for receiving the entire request from the client.

If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.

It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.

server.setTimeout([msecs][, callback])#

Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's 'timeout' event, timeouts must be handled explicitly.

server.maxRequestsPerSocket#

Added in: v16.10.0

The maximum number of requests socket can handle before closing keep alive connection.

A value of 0 will disable the limit.

When the limit is reached it will set the Connection header value to close, but will not actually close the connection, subsequent requests sent after the limit is reached will get 503 Service Unavailable as a response.

server.timeout#

The number of milliseconds of inactivity before a socket is presumed to have timed out.

A value of 0 will disable the timeout behavior on incoming connections.

The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

server.keepAliveTimeout#

Added in: v8.0.0

The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e.,server.timeout.

A value of 0 will disable the keep-alive timeout behavior on incoming connections. A value of 0 makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.

The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

Class: http.ServerResponse#

Added in: v0.1.17

This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.

Event: 'close'#

Added in: v0.6.7

Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion).

Event: 'finish'#

Added in: v0.3.6

Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.

response.addTrailers(headers)#

Added in: v0.3.0

This method adds HTTP trailing headers (a header but at the end of the message) to the response.

Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.

HTTP requires the Trailer header to be sent in order to emit trailers, with a list of the header fields in its value. E.g.,

response.writeHead(200, { 'Content-Type': 'text/plain',
                          'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

response.connection#

Added in: v0.3.0Deprecated since: v13.0.0

See response.socket.

response.cork()#

Added in: v13.2.0, v12.16.0

See writable.cork().

response.end([data[, encoding]][, callback])#

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is similar in effect to callingresponse.write(data, encoding) followed by response.end(callback).

If callback is specified, it will be called when the response stream is finished.

response.finished#

Added in: v0.0.2Deprecated since: v13.4.0, v12.16.0

The response.finished property will be true if response.end()has been called.

response.flushHeaders()#

Added in: v1.6.0

Flushes the response headers. See also: request.flushHeaders().

response.getHeader(name)#

Added in: v0.4.0

Reads out a header that's already been queued but not sent to the client. The name is case-insensitive. The type of the return value depends on the arguments provided to response.setHeader().

response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]

response.getHeaderNames()#

Added in: v7.7.0

Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.

response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']

response.getHeaders()#

Added in: v7.7.0

Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

The object returned by the response.getHeaders() method _does not_prototypically inherit from the JavaScript Object. This means that typicalObject methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }

response.hasHeader(name)#

Added in: v7.7.0

Returns true if the header identified by name is currently set in the outgoing headers. The header name matching is case-insensitive.

const hasContentType = response.hasHeader('content-type');

response.headersSent#

Added in: v0.9.3

Boolean (read-only). True if headers were sent, false otherwise.

response.removeHeader(name)#

Added in: v0.4.0

Removes a header that's queued for implicit sending.

response.removeHeader('Content-Encoding');

response.req#

Added in: v15.7.0

A reference to the original HTTP request object.

response.sendDate#

Added in: v0.7.5

When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.

This should only be disabled for testing; HTTP requires the Date header in responses.

response.setHeader(name, value)#

Added in: v0.4.0

Returns the response object.

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, response.getHeader() may return non-string values. However, the non-string values will be converted to strings for network transmission. The same response object is returned to the caller, to enable call chaining.

response.setHeader('Content-Type', 'text/html');

or

response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

// Returns content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});

If response.writeHead() method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, useresponse.setHeader() instead of response.writeHead().

response.setTimeout(msecs[, callback])#

Added in: v0.9.12

Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.

If no 'timeout' listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If a handler is assigned to the request, the response, or the server's 'timeout' events, timed out sockets must be handled explicitly.

response.socket#

Added in: v0.3.0

Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit 'readable' events because of how the protocol parser attaches to the socket. Afterresponse.end(), the property is nulled.

const http = require('http');
const server = http.createServer((req, res) => {
  const ip = res.socket.remoteAddress;
  const port = res.socket.remotePort;
  res.end(`Your IP address is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>i</mi><mi>p</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>y</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>s</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>c</mi><mi>e</mi><mi>p</mi><mi>o</mi><mi>r</mi><mi>t</mi><mi>i</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">{ip} and your source port is </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">i</span><span class="mord mathnormal">p</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal">yo</span><span class="mord mathnormal">u</span><span class="mord mathnormal">rso</span><span class="mord mathnormal">u</span><span class="mord mathnormal">rce</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span></span></span></span>{port}.`);
}).listen(3000);

This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket>.

response.statusCode#

Added in: v0.4.0

When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.

response.statusCode = 404;

After response header was sent to the client, this property indicates the status code which was sent out.

response.statusMessage#

Added in: v0.11.8

When using implicit headers (not calling response.writeHead() explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as undefined then the standard message for the status code will be used.

response.statusMessage = 'Not found';

After response header was sent to the client, this property indicates the status message which was sent out.

response.uncork()#

Added in: v13.2.0, v12.16.0

See writable.uncork().

response.writableEnded#

Added in: v12.9.0

Is true after response.end() has been called. This property does not indicate whether the data has been flushed, for this useresponse.writableFinished instead.

response.writableFinished#

Added in: v12.7.0

Is true if all data has been flushed to the underlying system, immediately before the 'finish' event is emitted.

response.write(chunk[, encoding][, callback])#

Added in: v0.1.29

If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.

This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.

In the http module, the response body is omitted when the request is a HEAD request. Similarly, the 204 and 304 responses_must not_ include a message body.

chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a byte stream.callback will be called when this chunk of data is flushed.

This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.

The first time response.write() is called, it will send the buffered header information and the first chunk of the body to the client. The second time response.write() is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory.'drain' will be emitted when the buffer is free again.

response.writeContinue()#

Added in: v0.3.0

Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event onServer.

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

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

headers may be an Array where the keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. The array is in the same format as request.rawHeaders.

Returns a reference to the ServerResponse, so that calls can be chained.

const body = 'hello world';
response
  .writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain'
  })
  .end(body);

This method must only be called once on a message and it must be called before response.end() is called.

If response.write() or response.end() are called before calling this, the implicit/mutable headers will be calculated and call this function.

When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, useresponse.setHeader() instead.

// Returns content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});

Content-Length is given in bytes, not characters. UseBuffer.byteLength() to determine the length of the body in bytes. Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

response.writeProcessing()#

Added in: v10.0.0

Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.

Class: http.IncomingMessage#

An IncomingMessage object is created by http.Server orhttp.ClientRequest and passed as the first argument to the 'request'and 'response' event respectively. It may be used to access response status, headers and data.

Different from its socket value which is a subclass of <stream.Duplex>, theIncomingMessage itself extends <stream.Readable> and is created separately to parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive.

Event: 'aborted'#

Added in: v0.3.8Deprecated since: v17.0.0

Stability: 0 - Deprecated. Listen for 'close' event instead.

Emitted when the request has been aborted.

Event: 'close'#

Emitted when the request has been completed.

message.aborted#

Added in: v10.1.0Deprecated since: v17.0.0

The message.aborted property will be true if the request has been aborted.

message.complete#

Added in: v0.3.0

The message.complete property will be true if a complete HTTP message has been received and successfully parsed.

This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:

const req = http.request({
  host: '127.0.0.1',
  port: 8080,
  method: 'POST'
}, (res) => {
  res.resume();
  res.on('end', () => {
    if (!res.complete)
      console.error(
        'The connection was terminated while the message was still being sent');
  });
});

message.connection#

Added in: v0.1.90Deprecated since: v16.0.0

Alias for message.socket.

message.destroy([error])#

Calls destroy() on the socket that received the IncomingMessage. If erroris provided, an 'error' event is emitted on the socket and error is passed as an argument to any listeners on the event.

message.headers#

The request/response headers object.

Key-value pairs of header names and values. Header names are lower-cased.

// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
//   host: '127.0.0.1:8000',
//   accept: '*/*' }
console.log(request.headers);

Duplicates in raw headers are handled in the following ways, depending on the header name:

message.httpVersion#

Added in: v0.1.1

In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

Also message.httpVersionMajor is the first integer andmessage.httpVersionMinor is the second.

message.method#

Added in: v0.1.1

Only valid for request obtained from http.Server.

The request method as a string. Read only. Examples: 'GET', 'DELETE'.

message.rawHeaders#

Added in: v0.11.6

The raw request/response headers list exactly as they were received.

The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.

Header names are not lowercased, and duplicates are not merged.

// Prints something like:
//
// [ 'user-agent',
//   'this is invalid because there can be only one',
//   'User-Agent',
//   'curl/7.22.0',
//   'Host',
//   '127.0.0.1:8000',
//   'ACCEPT',
//   '*/*' ]
console.log(request.rawHeaders);

message.rawTrailers#

Added in: v0.11.6

The raw request/response trailer keys and values exactly as they were received. Only populated at the 'end' event.

message.setTimeout(msecs[, callback])#

Added in: v0.5.9

Calls message.socket.setTimeout(msecs, callback).

message.socket#

Added in: v0.3.0

The net.Socket object associated with the connection.

With HTTPS support, use request.socket.getPeerCertificate() to obtain the client's authentication details.

This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket> or internally nulled.

message.statusCode#

Added in: v0.1.1

Only valid for response obtained from http.ClientRequest.

The 3-digit HTTP response status code. E.G. 404.

message.statusMessage#

Added in: v0.11.10

Only valid for response obtained from http.ClientRequest.

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

message.trailers#

Added in: v0.3.0

The request/response trailers object. Only populated at the 'end' event.

message.url#

Added in: v0.1.90

Only valid for request obtained from http.Server.

Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:

GET /status?name=ryan HTTP/1.1
Accept: text/plain

To parse the URL into its parts:

new URL(request.url, `http://${request.headers.host}`);

When request.url is '/status?name=ryan' andrequest.headers.host is 'localhost:3000':

$ node
> new URL(request.url, `http://${request.headers.host}`)
URL {
  href: 'http://localhost:3000/status?name=ryan',
  origin: 'http://localhost:3000',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:3000',
  hostname: 'localhost',
  port: '3000',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}

Class: http.OutgoingMessage#

Added in: v0.1.17

This class serves as the parent class of http.ClientRequestand http.ServerResponse. It is an abstract of outgoing message from the perspective of the participants of HTTP transaction.

Event: 'drain'#

Added in: v0.3.6

Emitted when the buffer of the message is free again.

Event: 'finish'#

Added in: v0.1.17

Emitted when the transmission is finished successfully.

Event: 'prefinish'#

Added in: v0.11.6

Emitted when outgoingMessage.end was called. When the event is emitted, all data has been processed but not necessarily completely flushed.

outgoingMessage.addTrailers(headers)#

Added in: v0.3.0

Adds HTTP trailers (headers but at the end of the message) to the message.

Trailers are only be emitted if the message is chunked encoded. If not, the trailer will be silently discarded.

HTTP requires the Trailer header to be sent to emit trailers, with a list of header fields in its value, e.g.

message.writeHead(200, { 'Content-Type': 'text/plain',
                         'Trailer': 'Content-MD5' });
message.write(fileData);
message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
message.end();

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

outgoingMessage.connection#

Added in: v0.3.0Deprecated since: v15.12.0, v14.17.1

Aliases of outgoingMessage.socket

outgoingMessage.cork()#

Added in: v14.0.0

See writable.cork().

outgoingMessage.destroy([error])#

Added in: v0.3.0

Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well.

outgoingMessage.end(chunk[, encoding][, callback])#

Finishes the outgoing message. If any parts of the body are unsent, it will flush them to the underlying system. If the message is chunked, it will send the terminating chunk 0\r\n\r\n, and send the trailer (if any).

If chunk is specified, it is equivalent to calloutgoingMessage.write(chunk, encoding), followed byoutgoingMessage.end(callback).

If callback is provided, it will be called when the message is finished. (equivalent to the callback to event finish)

outgoingMessage.flushHeaders()#

Added in: v1.6.0

Compulsorily flushes the message headers

For efficiency reason, Node.js normally buffers the message headers until outgoingMessage.end() is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet.

It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. outgoingMessage.flushHeaders()bypasses the optimization and kickstarts the request.

outgoingMessage.getHeader(name)#

Added in: v0.4.0

Gets the value of HTTP header with the given name. If such a name doesn't exist in message, it will be undefined.

outgoingMessage.getHeaderNames()#

Added in: v8.0.0

Returns an array of names of headers of the outgoing outgoingMessage. All names are lowercase.

outgoingMessage.getHeaders()#

Added in: v8.0.0

Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

The object returned by the outgoingMessage.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }

outgoingMessage.hasHeader(name)#

Added in: v8.0.0

Returns true if the header identified by name is currently set in the outgoing headers. The header name is case-insensitive.

const hasContentType = outgoingMessage.hasHeader('content-type');

outgoingMessage.headersSent#

Added in: v0.9.3

Read-only. true if the headers were sent, otherwise false.

outgoingMessage.pipe()#

Added in: v9.0.0

Overrides the pipe method of legacy Stream which is the parent class ofhttp.outgoingMessage.

Since OutgoingMessage should be a write-only stream, call this function will throw an Error. Thus, it disabled the pipe method it inherits from Stream.

The User should not call this function directly.

outgoingMessage.removeHeader()#

Added in: v0.4.0

Removes a header that is queued for implicit sending.

outgoingMessage.removeHeader('Content-Encoding');

outgoingMessage.setHeader(name, value)#

Added in: v0.4.0

Sets a single header value for the header object.

outgoingMessage.setTimeout(msesc[, callback])#

Added in: v0.9.12

Once a socket is associated with the message and is connected,socket.setTimeout() will be called with msecs as the first parameter.

outgoingMessage.socket#

Added in: v0.3.0

Reference to the underlying socket. Usually, users will not want to access this property.

After calling outgoingMessage.end(), this property will be nulled.

outgoingMessage.uncork()#

Added in: v14.0.0

See writable.uncork()

outgoingMessage.writableCorked#

Added in: v14.0.0

This outgoingMessage.writableCorked will return the time how manyoutgoingMessage.cork() have been called.

outgoingMessage.writableEnded#

Added in: v13.0.0

Readonly, true if outgoingMessage.end() has been called. Noted that this property does not reflect whether the data has been flush. For that purpose, use message.writableFinished instead.

outgoingMessage.writableFinished#

Added in: v13.0.0

Readonly. true if all data has been flushed to the underlying system.

outgoingMessage.writableHighWaterMark#

Added in: v13.0.0

This outgoingMessage.writableHighWaterMark will be the highWaterMark of underlying socket if socket exists. Else, it would be the defaulthighWaterMark.

highWaterMark is the maximum amount of data that can be potentially buffered by the socket.

outgoingMessage.writableLength#

Added in: v13.0.0

Readonly, This outgoingMessage.writableLength contains the number of bytes (or objects) in the buffer ready to send.

outgoingMessage.writableObjectMode#

Added in: v13.0.0

Readonly, always returns false.

outgoingMessage.write(chunk[, encoding][, callback])#

If this method is called and the header is not sent, it will callthis._implicitHeader to flush implicit header. If the message should not have a body (indicated by this._hasBody), the call is ignored and chunk will not be sent. It could be useful when handling a particular message which must not include a body. e.g. response to HEAD request, 204 and 304 response.

chunk can be a string or a buffer. When chunk is a string, theencoding parameter specifies how to encode chunk into a byte stream.callback will be called when the chunk is flushed.

If the message is transferred in chucked encoding (indicated by this.chunkedEncoding), chunk will be flushed as one chunk among a stream of chunks. Otherwise, it will be flushed as the body of message.

This method handles the raw body of the HTTP message and has nothing to do with higher-level multi-part body encodings that may be used.

If it is the first call to this method of a message, it will send the buffered header first, then flush the chunk as described above.

The second and successive calls to this method will assume the data will be streamed and send the new data separately. It means that the response is buffered up to the first chunk of the body.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in the user memory. Event drain will be emitted when the buffer is free again.

http.METHODS#

Added in: v0.11.8

A list of the HTTP methods that are supported by the parser.

http.STATUS_CODES#

Added in: v0.1.22

A collection of all the standard HTTP response status codes, and the short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

http.createServer([options][, requestListener])#

Returns a new instance of http.Server.

The requestListener is a function which is automatically added to the 'request' event.

const http = require('http');

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(8000);
const http = require('http');

// Create a local server to receive data from
const server = http.createServer();

// Listen to the request event
server.on('request', (request, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(8000);

http.get(options[, callback])#

http.get(url[, options][, callback])#

Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method andhttp.request() is that it sets the method to GET and calls req.end()automatically. The callback must take care to consume the response data for reasons stated in http.ClientRequest section.

The callback is invoked with a single argument that is an instance ofhttp.IncomingMessage.

JSON fetching example:

http.get('http://localhost:8000/', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  // Any 2xx status code signals a successful response but
  // here we're only checking for 200.
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // Consume response data to free up memory
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen(8000);

http.globalAgent#

Added in: v0.5.9

Global instance of Agent which is used as the default for all HTTP client requests.

http.maxHeaderSize#

Added in: v11.6.0, v10.15.0

Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 16 KB. Configurable using the --max-http-header-size CLI option.

This can be overridden for servers and client requests by passing themaxHeaderSize option.

http.request(options[, callback])#

http.request(url[, options][, callback])#

options in socket.connect() are also supported.

Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

url can be a string or a URL object. If url is a string, it is automatically parsed with new URL(). If it is a URLobject, it will be automatically converted to an ordinary options object.

If both url and options are specified, the objects are merged, with theoptions properties taking precedence.

The optional callback parameter will be added as a one-time listener for the 'response' event.

http.request() returns an instance of the http.ClientRequestclass. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

const http = require('http');

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

In the example req.end() was called. With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object. As with all 'error' events, if no listeners are registered the error will be thrown.

There are a few special headers that should be noted.

Example using a URL as options:

const options = new URL('http://abc:[email protected]');

const req = http.request(options, (res) => {
  // ...
});

In a successful request, the following events will be emitted in the following order:

In the case of a connection error, the following events will be emitted:

In the case of a premature connection close before the response is received, the following events will be emitted in the following order:

In the case of a premature connection close after the response is received, the following events will be emitted in the following order:

If req.destroy() is called before a socket is assigned, the following events will be emitted in the following order:

If req.destroy() is called before the connection succeeds, the following events will be emitted in the following order:

If req.destroy() is called after the response is received, the following events will be emitted in the following order:

If req.abort() is called before a socket is assigned, the following events will be emitted in the following order:

If req.abort() is called before the connection succeeds, the following events will be emitted in the following order:

If req.abort() is called after the response is received, the following events will be emitted in the following order:

Setting the timeout option or using the setTimeout() function will not abort the request or do anything besides add a 'timeout' event.

Passing an AbortSignal and then calling abort on the correspondingAbortController will behave the same way as calling .destroy() on the request itself.

http.validateHeaderName(name)#

Added in: v14.3.0

Performs the low-level validations on the provided name that are done whenres.setHeader(name, value) is called.

Passing illegal value as name will result in a TypeError being thrown, identified by code: 'ERR_INVALID_HTTP_TOKEN'.

It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers. Examples:

Example:

const { validateHeaderName } = require('http');

try {
  validateHeaderName('');
} catch (err) {
  err instanceof TypeError; // --> true
  err.code; // --> 'ERR_INVALID_HTTP_TOKEN'
  err.message; // --> 'Header name must be a valid HTTP token [""]'
}

http.validateHeaderValue(name, value)#

Added in: v14.3.0

Performs the low-level validations on the provided value that are done whenres.setHeader(name, value) is called.

Passing illegal value as value will result in a TypeError being thrown.

It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

Examples:

const { validateHeaderValue } = require('http');

try {
  validateHeaderValue('x-my-header', undefined);
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
  err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
}

try {
  validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_INVALID_CHAR'; // --> true
  err.message; // --> 'Invalid character in header content ["x-my-header"]'
}