Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns
Node.js http.request() method
Reference for http.request() in Node.js: build a client request with options, write a body, read the response stream, set timeouts and handle errors.
http.request() starts an HTTP client request and returns an http.ClientRequest. It is the low-level client in node:http: you choose the method, headers and body, you write the body yourself, and you receive the response as a readable stream. The request is not sent until you call req.end(), because Node cannot know whether more body data is coming.
For everyday work the global fetch() is shorter, but http.request() gives direct control over agents, sockets, raw headers and trailers. Use http.get() for GET requests without a body; it calls end() for you.
const req = http.request({ host: '127.0.0.1', port: 3000, method: 'POST' }, (res) => { // res is an http.IncomingMessage }); req.end('body');
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
http.request(options[, callback]) http.request(url[, options][, callback]) // returns http.ClientRequest
| Name | Description |
|---|---|
url |
A string or URL. It is parsed into protocol, host, port, path and any credentials. Fields in options override the parsed ones. |
options.method |
HTTP method, default 'GET'. |
options.host / options.hostname |
Server name or address, default 'localhost'. If both are given, hostname wins. |
options.port |
Port, default 80 (or the agent's default port). |
options.path |
Request target including the query string, default '/'. Must not contain spaces or control characters. |
options.headers |
Object of request headers. |
options.auth |
'user:password', sent as a Basic Authorization header. |
options.agent |
An http.Agent, false for a fresh one-off agent, or undefined for the global agent. |
options.timeout |
Socket idle timeout in milliseconds; emits 'timeout' but does not abort. |
options.signal |
An AbortSignal that destroys the request when aborted. |
options.setHost |
Set to false to stop Node adding a Host header automatically. |
options.localAddress, options.family, options.lookup |
Control which local address and DNS family or resolver the socket uses. |
options.maxHeaderSize, options.insecureHTTPParser |
Header parser limits and leniency (leave the second one alone). |
options.createConnection |
A function that returns the socket to use instead of opening a TCP connection. |
callback |
Added as a one-time listener for the 'response' event. |
Returns: an http.ClientRequest, a writable stream.
Errors: invalid options throw synchronously (ERR_INVALID_ARG_TYPE, ERR_INVALID_HTTP_TOKEN for a bad method, ERR_UNESCAPED_CHARACTERS for a bad path). Network failures (ECONNREFUSED, ECONNRESET, ENOTFOUND) are emitted as 'error' on the request, so always attach an error listener.
Usage notes
- Call
req.end(). Without it the request never leaves the process.req.end(data)writes the last chunk and finishes in one call. - Always handle
'error'. An unhandled'error'event on the request crashes the process. - Consume the response. If you ignore the
IncomingMessage, callres.resume()so the connection can be freed. A response you never read keeps its socket busy. - Set the body length. With no
Content-Lengthand noTransfer-Encoding, Node uses chunked encoding automatically for bodies written in several pieces; for one string, settingContent-Lengthis cleaner. - No redirects, no JSON, no status checks.
http.request()returns a404or301as a normal response. Redirect following, decoding and retries are yours to write, or usefetch(). - Timeouts:
timeoutis an idle timer on the socket, not a total deadline. For a deadline useAbortSignal.timeout(). - Connection reuse is decided by the agent. The global agent uses keep-alive by default since Node 19; see
http.Agent. - HTTPS uses the same API from
node:https; seehttps.request().