Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns
Node.js http.ClientRequest class
Reference for http.ClientRequest in Node.js: the writable request object returned by http.request(), its events, headers, body writing, abort and timeout handling.
http.ClientRequest is the object returned by http.request() and http.get(). It is a writable stream for the request body, and an event emitter that reports what happens on the wire: the response, interim 1xx messages, socket assignment, timeouts and errors. You never construct it with new.
The request is "in flight" from the moment it is created, but its headers are only sent when the first body chunk is written or end() is called. Until then you can still change headers with setHeader().
const req = http.request({ host: '127.0.0.1', port: 3000, method: 'PUT' }); req.setHeader('X-Token', 'abc'); req.on('response', (res) => res.resume()); req.end('payload');
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
class http.ClientRequest extends http.OutgoingMessage // a Writable stream
Events
| Event | Description |
|---|---|
'response' |
The final response head arrived; argument is an http.IncomingMessage. If you have no listener, the response is discarded. |
'information' |
An interim 1xx response (such as 103) arrived; argument has statusCode, headers and httpVersion. |
'socket' |
A socket was assigned to the request. |
'connect' |
The server answered a CONNECT request. |
'upgrade' |
The server answered with 101 Switching Protocols or similar. |
'continue' |
The server sent 100 Continue after an Expect: 100-continue request. |
'timeout' |
The socket was idle longer than the configured timeout. The request is not aborted for you. |
'finish' |
The request body has been handed to the operating system. |
'error' |
The request failed (connection, parsing, or destroy(err)). |
'close' |
The request is done and its resources are released. |
Methods and properties
| Name | Description |
|---|---|
req.write(chunk[, encoding][, cb]) / req.end([data]) |
Write body data and finish. |
req.setHeader(name, value), getHeader(), getHeaders(), getHeaderNames(), hasHeader(), removeHeader() |
Edit headers before they are sent. |
req.flushHeaders() |
Send the headers now, without waiting for the first body chunk. |
req.destroy([err]) |
Abort the request and its socket. Given an error, that error is emitted; without one, a request destroyed before any response still emits ECONNRESET ("socket hang up"). |
req.setTimeout(ms[, cb]) |
Idle timeout for the socket; the callback is a 'timeout' listener. |
req.setNoDelay(), req.setSocketKeepAlive() |
Socket tuning. |
req.method, req.path, req.host, req.protocol |
Description of the request. |
req.headersSent, req.writableEnded, req.destroyed, req.reusedSocket |
State flags. |
req.socket |
The underlying net.Socket (also req.connection, deprecated). |
req.abort() |
Deprecated; use destroy(). |
Errors: setHeader() after the headers were sent throws ERR_HTTP_HEADERS_SENT. Writing after end() emits an error (ERR_STREAM_WRITE_AFTER_END).
Usage notes
'error'is mandatory. A request without an error listener turns a refused connection into an uncaught exception.'timeout'does nothing by itself. You must callreq.destroy()inside the handler, or usesignal: AbortSignal.timeout(ms)in the options.'response'fires once per final response. If you attach no listener, Node discards the response data, which frees the socket but gives you nothing.- Slow bodies:
write()returnsfalsewhen the buffer is full; wait for'drain'before writing more, or usestream.pipeline()to feed a request from a file. Expect: 100-continue: set the header and wait for'continue'before sending a big upload, so a rejected request costs nothing.flushHeaders()is useful for long-lived requests (streaming uploads) where the server should see the headers before any body exists.- Socket reuse:
req.reusedSockettells you whether a keep-alive connection from the agent carried this request. A server that closes an idle socket just before reuse causesECONNRESET; retrying idempotent requests is the usual remedy. - Redirects are not followed.
fetch()does that for you.