Class ClientRequest

This object is created internally and returned from 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 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.

Hierarchy

  • ClientRequest

Constructors

Properties

aborted: boolean

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

Deprecated

Since v17.0.0,v16.12.0 - Check destroyed instead.

host: string

The request host.

maxHeadersCount: number

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

method: string

The request method.

path: string

The request path.

protocol: string

The request protocol.

reusedSocket: boolean

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

Methods

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

    Deprecated

    Since v14.1.0,v13.14.0 - Use destroy instead.

    Returns void

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

    Returns void

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

    Parameters

    • name: string

      Name of header

    Returns string | number | string[]

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

    Returns string[]

  • Removes a header that is queued for implicit sending.

    outgoingMessage.removeHeader('Content-Encoding');
    

    Parameters

    • name: string

      Header name

    Returns void

  • Sets a single header value for the header object.

    Parameters

    • name: string

      Header name

    • value: string | number | readonly string[]

      Header value

    Returns "http".ClientRequest

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

    Parameters

    • Optional noDelay: boolean

    Returns void

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

    Parameters

    • Optional enable: boolean
    • Optional initialDelay: number

    Returns void

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

    Parameters

    • timeout: number

      Milliseconds before a request times out.

    • Optional callback: (() => void)

      Optional function to be called when a timeout occurs. Same as binding to the 'timeout' event.

        • (): void
        • Returns void

    Returns "http".ClientRequest

Generated using TypeDoc