HTTP#
Source Code:lib/http.js
This module, containing both a client and server, can be imported viarequire('node:http') (CommonJS) orimport * as http from 'node:http' (ES module).
The HTTP interfaces in Node.js are designed to support many featuresof the protocol which have been traditionally difficult to use.In particular, large, possibly chunk-encoded, messages. The interface iscareful to never buffer entire requests or responses, so theuser 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.jsHTTP API is very low-level. It deals with stream handling and messageparsing only. It parses a message into headers and body but it does notparse the actual headers or the body.
Seemessage.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in therawHeadersproperty, which is an array of[key, value, key2, value2, ...]. Forexample, the previous message header object might have arawHeaderslist like the following:
['ConTent-Length','123456','content-LENGTH','123','content-type','text/plain','CONNECTION','keep-alive','Host','example.com','accepT','*/*' ]Class:http.Agent#
AnAgent is responsible for managing connection persistenceand reuse for HTTP clients. It maintains a queue of pending requestsfor a given host and port, reusing a single socket connection for eachuntil the queue is empty, at which time the socket is either destroyedor put into a pool where it is kept to be used again for requests to thesame host and port. Whether it is destroyed or pooled depends on thekeepAliveoption.
Pooled connections have TCP Keep-Alive enabled for them, but servers maystill close idle connections, in which case they will be removed from thepool and a new connection will be made when a new HTTP request is made forthat host and port. Servers may also refuse to allow multiple requestsover the same connection, in which case the connection will have to beremade for every request and cannot be pooled. TheAgent will still makethe 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 removedfrom the pool. Any unused sockets in the pool will be unrefed so as notto keep the Node.js process running when there are no outstanding requests.(seesocket.unref()).
It is good practice, todestroy() anAgent instance when it is nolonger in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits eithera'close' event or an'agentRemove' event. When intending to keep oneHTTP request open for a long time without keeping it in the agent, somethinglike 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 thehttp.get() orhttp.request()functions, a one-time useAgent with default options will be usedfor 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])#
History
| Version | Changes |
|---|---|
| v24.5.0 | Add support for |
| v24.5.0 | Add support for |
| v24.7.0, v22.20.0 | Add support for |
| v15.6.0, v14.17.0 | Change the default scheduling from 'fifo' to 'lifo'. |
| v14.5.0, v12.20.0 | Add |
| v14.5.0, v12.19.0 | Add |
| v0.3.4 | Added in: v0.3.4 |
options<Object> Set of configurable options to set on the agent.Can have the following fields:keepAlive<boolean> Keep sockets around even when there are nooutstanding requests, so they can be used for future requests withouthaving to reestablish a TCP connection. Not to be confused with thekeep-alivevalue of theConnectionheader. TheConnection: keep-aliveheader is always sent when using an agent except when theConnectionheader is explicitly specified or when thekeepAliveandmaxSocketsoptions are respectively set tofalseandInfinity, in which caseConnection: closewill be used.Default:false.keepAliveMsecs<number> When using thekeepAliveoption, specifiestheinitial delayfor TCP Keep-Alive packets. Ignored when thekeepAliveoption isfalseorundefined.Default:1000.agentKeepAliveTimeoutBuffer<number> Milliseconds to subtract fromthe server-providedkeep-alive: timeout=...hint when determining socketexpiration time. This buffer helps ensure the agent closes the socketslightly before the server does, reducing the chance of sending a requeston a socket that’s about to be closed by the server.Default:1000.maxSockets<number> Maximum number of sockets to allow per host.If the same host opens multiple concurrent connections, each requestwill use new socket until themaxSocketsvalue is reached.If the host attempts to open more connections thanmaxSockets,the additional requests will enter into a pending request queue, andwill enter active connection state when an existing connection terminates.This makes sure there are at mostmaxSocketsactive connections atany point in time, from a given host.Default:Infinity.maxTotalSockets<number> Maximum number of sockets allowed forall hosts in total. Each request will use a new socketuntil the maximum is reached.Default:Infinity.maxFreeSockets<number> Maximum number of sockets per host to leave openin a free state. Only relevant ifkeepAliveis set totrue.Default:256.scheduling<string> Scheduling strategy to apply when pickingthe next free socket to use. It can be'fifo'or'lifo'.The main difference between the two scheduling strategies is that'lifo'selects the most recently used socket, while'fifo'selectsthe least recently used socket.In case of a low rate of request per second, the'lifo'schedulingwill lower the risk of picking a socket that might have been closedby the server due to inactivity.In case of a high rate of request per second,the'fifo'scheduling will maximize the number of open sockets,while the'lifo'scheduling will keep it as low as possible.Default:'lifo'.timeout<number> Socket timeout in milliseconds.This will set the timeout when the socket is created.proxyEnv<Object> |<undefined> Environment variables for proxy configuration.SeeBuilt-in Proxy Support for details.Default:undefinedHTTP_PROXY<string> |<undefined> URL for the proxy server that HTTP requests should use.If undefined, no proxy is used for HTTP requests.HTTPS_PROXY<string> |<undefined> URL for the proxy server that HTTPS requests should use.If undefined, no proxy is used for HTTPS requests.NO_PROXY<string> |<undefined> Patterns specifying the endpointsthat should not be routed through a proxy.http_proxy<string> |<undefined> Same asHTTP_PROXY. If both are set,http_proxytakes precedence.https_proxy<string> |<undefined> Same asHTTPS_PROXY. If both are set,https_proxytakes precedence.no_proxy<string> |<undefined> Same asNO_PROXY. If both are set,no_proxytakes precedence.
defaultPort<number> Default port to use when the port is not specifiedin requests.Default:80.protocol<string> The protocol to use for the agent.Default:'http:'.
options insocket.connect() are also supported.
To configure any of them, a customhttp.Agent instance must be created.
import {Agent, request }from'node:http';const keepAliveAgent =newAgent({keepAlive:true });options.agent = keepAliveAgent;request(options, onResponseCallback);const http =require('node:http');const keepAliveAgent =new http.Agent({keepAlive:true });options.agent = keepAliveAgent;http.request(options, onResponseCallback);
agent.createConnection(options[, callback])#
options<Object> Options containing connection details. Checknet.createConnection()for the format of the options. For custom agents,this object is passed to the customcreateConnectionfunction.callback<Function> (Optional, primarily for custom agents) A function to becalled by a customcreateConnectionimplementation when the socket iscreated, especially for asynchronous operations.err<Error> |<null> An error object if socket creation failed.socket<stream.Duplex> The created socket.
- Returns:<stream.Duplex> The created socket. This is returned by the defaultimplementation or by a custom synchronous
createConnectionimplementation.If a customcreateConnectionuses thecallbackfor asynchronousoperation, this return value might not be the primary way to obtain the socket.
Produces a socket/stream to be used for HTTP requests.
By default, this function behaves identically tonet.createConnection(),synchronously returning the created socket. The optionalcallback parameter in thesignature isnot used by this default implementation.
However, custom agents may override this method to provide greater flexibility,for example, to create sockets asynchronously. When overridingcreateConnection:
- Synchronous socket creation: The overriding method can return thesocket/stream directly.
- Asynchronous socket creation: The overriding method can accept the
callbackand pass the created socket/stream to it (e.g.,callback(null, newSocket)).If an error occurs during socket creation, it should be passed as the firstargument to thecallback(e.g.,callback(err)).
The agent will call the providedcreateConnection function withoptions andthis internalcallback. Thecallback provided by the agent has a signatureof(err, stream).
agent.keepSocketAlive(socket)#
socket<stream.Duplex>
Called whensocket is detached from a request and could be persisted by theAgent. Default behavior is to:
socket.setKeepAlive(true,this.keepAliveMsecs);socket.unref();returntrue;This method can be overridden by a particularAgent subclass. If thismethod returns a falsy value, the socket will be destroyed instead of persistingit for use with the next request.
Thesocket argument can be an instance of<net.Socket>, a subclass of<stream.Duplex>.
agent.reuseSocket(socket, request)#
socket<stream.Duplex>request<http.ClientRequest>
Called whensocket is attached torequest after being persisted because ofthe keep-alive options. Default behavior is to:
socket.ref();This method can be overridden by a particularAgent subclass.
Thesocket argument can be an instance of<net.Socket>, a subclass of<stream.Duplex>.
agent.destroy()#
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using anagent withkeepAlive enabled, then it is best to explicitly shut downthe agent when it is no longer needed. Otherwise,sockets might stay open for quite a long time before the serverterminates them.
agent.freeSockets#
History
| Version | Changes |
|---|---|
| v16.0.0 | The property now has a |
| v0.11.4 | Added in: v0.11.4 |
- Type:<Object>
An object which contains arrays of sockets currently awaiting use bythe agent whenkeepAlive is enabled. Do not modify.
Sockets in thefreeSockets list will be automatically destroyed andremoved from the array on'timeout'.
agent.getName([options])#
History
| Version | Changes |
|---|---|
| v17.7.0, v16.15.0 | The |
| v0.11.4 | Added in: v0.11.4 |
Get a unique name for a set of request options, to determine whether aconnection can be reused. For an HTTP agent, this returnshost:port:localAddress orhost:port:localAddress:family. For an HTTPS agent,the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific optionsthat determine socket reusability.
agent.maxFreeSockets#
- Type:<number>
By default set to 256. For agents withkeepAlive enabled, thissets the maximum number of sockets that will be left open in the freestate.
agent.maxSockets#
- Type:<number>
By default set toInfinity. Determines how many concurrent sockets the agentcan have open per origin. Origin is the returned value ofagent.getName().
agent.maxTotalSockets#
- Type:<number>
By default set toInfinity. Determines how many concurrent sockets the agentcan have open. UnlikemaxSockets, this parameter applies across all origins.
Class:http.ClientRequest#
- Extends:<http.OutgoingMessage>
This object is created internally and returned fromhttp.request(). Itrepresents anin-progress request whose header has already been queued. Theheader is still mutable using thesetHeader(name, value),getHeader(name),removeHeader(name) API. The actual header willbe sent along with the first data chunk or when callingrequest.end().
To get the response, add a listener for'response' to the request object.'response' will be emitted from the request object when the responseheaders have been received. The'response' event is executed with oneargument which is an instance ofhttp.IncomingMessage.
During the'response' event, one can add listeners to theresponse object; particularly to listen for the'data' event.
If no'response' handler is added, then the response will beentirely discarded. However, if a'response' event handler is added,then the data from the response objectmust be consumed, either bycallingresponse.read() whenever there is a'readable' event, orby adding a'data' handler, or by calling the.resume() method.Until the data is consumed, the'end' event will not fire. Also, untilthe 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.
SetContent-Length header to limit the response body size.Ifresponse.strictContentLength is set totrue, mismatching theContent-Length header value will result in anError being thrown,identified bycode:'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Content-Length value should be in bytes, not characters. UseBuffer.byteLength() to determine the length of the body in bytes.
Event:'abort'#
'close' event instead.Emitted when the request has been aborted by the client. This event is onlyemitted on the first call toabort().
Event:'close'#
Indicates that the request is completed, or its underlying connection wasterminated prematurely (before the response completion).
Event:'connect'#
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
Emitted each time a server responds to a request with aCONNECT method. Ifthis event is not being listened for, clients receiving aCONNECT method willhave 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 sockettype other than<net.Socket>.
A client and server pair demonstrating how to listen for the'connect' event:
import { createServer, request }from'node:http';import { connect }from'node:net';import {URL }from'node:url';// Create an HTTP tunneling proxyconst proxy =createServer((req, res) => { res.writeHead(200, {'Content-Type':'text/plain' }); res.end('okay');});proxy.on('connect',(req, clientSocket, head) => {// Connect to an origin serverconst { port, hostname } =newURL(`http://${req.url}`);const serverSocket =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 runningproxy.listen(1337,'127.0.0.1',() => {// Make a request to a tunneling proxyconst options = {port:1337,host:'127.0.0.1',method:'CONNECT',path:'www.google.com:80', };const req =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(); }); });});const http =require('node:http');const net =require('node:net');const {URL } =require('node:url');// Create an HTTP tunneling proxyconst 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 serverconst { port, hostname } =newURL(`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 runningproxy.listen(1337,'127.0.0.1',() => {// Make a request to a tunneling proxyconst 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'#
Emitted when the server sends a '100 Continue' HTTP response, usually becausethe request contained 'Expect: 100-continue'. This is an instruction thatthe client should send the request body.
Event:'finish'#
Emitted when the request has been sent. More specifically, this event is emittedwhen the last segment of the request headers and body have been handed off tothe operating system for transmission over the network. It does not imply thatthe server has received anything yet.
Event:'information'#
info<Object>
Emitted when the server sends a 1xx intermediate response (excluding 101Upgrade). The listeners of this event will receive an object containing theHTTP version, status code, status message, key-value headers object,and array with the raw header names followed by their respective values.
import { request }from'node:http';const options = {host:'127.0.0.1',port:8080,path:'/length_request',};// Make a requestconst req =request(options);req.end();req.on('information',(info) => {console.log(`Got information prior to main response:${info.statusCode}`);});const http =require('node:http');const options = {host:'127.0.0.1',port:8080,path:'/length_request',};// Make a requestconst 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 thetraditional HTTP request/response chain, such as web sockets, in-place TLSupgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the'upgrade' event instead.
Event:'response'#
response<http.IncomingMessage>
Emitted when a response is received to this request. This event is emitted onlyonce.
Event:'socket'#
socket<stream.Duplex>
This event is guaranteed to be passed an instance of the<net.Socket> class,a subclass of<stream.Duplex>, unless the user specifies a sockettype other than<net.Socket>.
Event:'timeout'#
Emitted when the underlying socket times out from inactivity. This only notifiesthat the socket has been idle. The request must be destroyed manually.
See also:request.setTimeout().
Event:'upgrade'#
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
Emitted each time a server responds to a request with an upgrade. If thisevent is not being listened for and the response status code is 101 SwitchingProtocols, clients receiving an upgrade header will have their connectionsclosed.
This event is guaranteed to be passed an instance of the<net.Socket> class,a subclass of<stream.Duplex>, unless the user specifies a sockettype other than<net.Socket>.
A client server pair demonstrating how to listen for the'upgrade' event.
import httpfrom'node:http';import processfrom'node:process';// Create an HTTP serverconst 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 runningserver.listen(1337,'127.0.0.1',() => {// make a requestconst 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); });});const http =require('node:http');// Create an HTTP serverconst 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 runningserver.listen(1337,'127.0.0.1',() => {// make a requestconst 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()#
request.destroy() instead.Marks the request as aborting. Calling this will cause remaining datain the response to be dropped and the socket to be destroyed.
request.aborted#
History
| Version | Changes |
|---|---|
| v17.0.0, v16.12.0 | Deprecated since: v17.0.0, v16.12.0 |
| v11.0.0 | The |
| v0.11.14 | Added in: v0.11.14 |
request.destroyed instead.- Type:<boolean>
Therequest.aborted property will betrue if the request hasbeen aborted.
request.connection#
request.socket.- Type:<stream.Duplex>
Seerequest.socket.
request.end([data[, encoding]][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v10.0.0 | This method now returns a reference to |
| v0.1.90 | Added in: v0.1.90 |
data<string> |<Buffer> |<Uint8Array>encoding<string>callback<Function>- Returns:<this>
Finishes sending the request. If any parts of the body areunsent, it will flush them to the stream. If the request ischunked, this will send the terminating'0\r\n\r\n'.
Ifdata is specified, it is equivalent to callingrequest.write(data, encoding) followed byrequest.end(callback).
Ifcallback is specified, it will be called when the request streamis finished.
request.destroy([error])#
History
| Version | Changes |
|---|---|
| v14.5.0 | The function returns |
| v0.3.0 | Added in: v0.3.0 |
Destroy the request. Optionally emit an'error' event,and emit a'close' event. Calling this will cause remaining datain the response to be dropped and the socket to be destroyed.
Seewritable.destroy() for further details.
request.destroyed#
- Type:<boolean>
Istrue afterrequest.destroy() has been called.
Seewritable.destroyed for further details.
request.finished#
request.writableEnded.- Type:<boolean>
Therequest.finished property will betrue ifrequest.end()has been called.request.end() will automatically be called if therequest was initiated viahttp.get().
request.flushHeaders()#
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. Itthen 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 firstdata is not sent until possibly much later.request.flushHeaders() bypassesthe optimization and kickstarts the request.
request.getHeader(name)#
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 numberconst cookie = request.getHeader('Cookie');// 'cookie' is of type string[]request.getHeaderNames()#
- Returns:<string[]>
Returns an array containing the unique names of the current outgoing headers.All header names are lowercase.
request.setHeader('Foo','bar');request.setHeader('Cookie', ['foo=bar','bar=baz']);const headerNames = request.getHeaderNames();// headerNames === ['foo', 'cookie']request.getHeaders()#
- Returns:<Object>
Returns a shallow copy of the current outgoing headers. Since a shallow copyis used, array values may be mutated without additional calls to variousheader-related http module methods. The keys of the returned object are theheader names and the values are the respective header values. All header namesare lowercase.
The object returned by therequest.getHeaders() methoddoes notprototypically inherit from the JavaScriptObject. This means that typicalObject methods such asobj.toString(),obj.hasOwnProperty(), and othersare not defined andwill not work.
request.setHeader('Foo','bar');request.setHeader('Cookie', ['foo=bar','bar=baz']);const headers = request.getHeaders();// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }request.getRawHeaderNames()#
- Returns:<string[]>
Returns an array containing the unique names of the current outgoing rawheaders. 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.hasHeader(name)#
Returnstrue if the header identified byname is currently set in theoutgoing headers. The header name matching is case-insensitive.
const hasContentType = request.hasHeader('content-type');request.maxHeadersCount#
- Type:<number>Default:
2000
Limits maximum response headers count. If set to 0, no limit will be applied.
request.removeHeader(name)#
name<string>
Removes a header that's already defined into headers object.
request.removeHeader('Content-Type');request.reusedSocket#
- Type:<boolean> Whether the request is send through a reused socket.
When sending request through a keep-alive enabled agent, the underlying socketmight be reused. But if server closes connection at unfortunate time, clientmay run into a 'ECONNRESET' error.
import httpfrom'node:http';const agent =new http.Agent({keepAlive:true });// Server has a 5 seconds keep-alive timeout by defaulthttp .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 timeoutconst http =require('node:http');const agent =new http.Agent({keepAlive:true });// Server has a 5 seconds keep-alive timeout by defaulthttp .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 doautomatic error retry base on it.
import httpfrom'node:http';const agent =new http.Agent({keepAlive:true });functionretriableRequest() {const req = http .get('http://localhost:3000', { agent },(res) => {// ... }) .on('error',(err) => {// Check if retry is neededif (req.reusedSocket && err.code ==='ECONNRESET') {retriableRequest(); } });}retriableRequest();const http =require('node:http');const agent =new http.Agent({keepAlive:true });functionretriableRequest() {const req = http .get('http://localhost:3000', { agent },(res) => {// ... }) .on('error',(err) => {// Check if retry is neededif (req.reusedSocket && err.code ==='ECONNRESET') {retriableRequest(); } });}retriableRequest();
request.setHeader(name, value)#
Sets a single header value for headers object. If this header already exists inthe to-be-sent headers, its value will be replaced. Use an array of stringshere to send multiple headers with the same name. Non-string values will bestored without modification. Therefore,request.getHeader() may returnnon-string values. However, the non-string values will be converted to stringsfor network transmission.
request.setHeader('Content-Type','application/json');or
request.setHeader('Cookie', ['type=ninja','language=javascript']);When the value is a string an exception will be thrown if it containscharacters outside thelatin1 encoding.
If you need to pass UTF-8 characters in the value please encode the valueusing theRFC 8187 standard.
const filename ='Rock 🎵.txt';request.setHeader('Content-Disposition',`attachment; filename*=utf-8''${encodeURIComponent(filename)}`);request.setNoDelay([noDelay])#
noDelay<boolean>
Once a socket is assigned to this request and is connectedsocket.setNoDelay() will be called.
request.setSocketKeepAlive([enable][, initialDelay])#
Once a socket is assigned to this request and is connectedsocket.setKeepAlive() will be called.
request.setTimeout(timeout[, callback])#
History
| Version | Changes |
|---|---|
| v9.0.0 | Consistently set socket timeout only when the socket connects. |
| v0.5.9 | Added in: v0.5.9 |
timeout<number> Milliseconds before a request times out.callback<Function> Optional function to be called when a timeout occurs.Same as binding to the'timeout'event.- Returns:<http.ClientRequest>
Once a socket is assigned to this request and is connectedsocket.setTimeout() will be called.
request.socket#
- Type:<stream.Duplex>
Reference to the underlying socket. Usually users will not want to accessthis property. In particular, the socket will not emit'readable' eventsbecause of how the protocol parser attaches to the socket.
import httpfrom'node: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${ip} and your source port is${port}.`);// Consume response object});const http =require('node: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${ip} and your source port is${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 sockettype other than<net.Socket>.
request.writableEnded#
- Type:<boolean>
Istrue afterrequest.end() has been called. This propertydoes not indicate whether the data has been flushed, for this userequest.writableFinished instead.
request.writableFinished#
- Type:<boolean>
Istrue if all data has been flushed to the underlying system, immediatelybefore the'finish' event is emitted.
request.write(chunk[, encoding][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v0.1.29 | Added in: v0.1.29 |
chunk<string> |<Buffer> |<Uint8Array>encoding<string>callback<Function>- Returns:<boolean>
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 Chunkedtransfer encoding, so that server knows when the data ends. TheTransfer-Encoding: chunked header is added. Callingrequest.end()is necessary to finish sending the request.
Theencoding argument is optional and only applies whenchunk is a string.Defaults to'utf8'.
Thecallback argument is optional and will be called when this chunk of datais flushed, but only if the chunk is non-empty.
Returnstrue if the entire data was flushed successfully to the kernelbuffer. Returnsfalse if all or part of the data was queued in user memory.'drain' will be emitted when the buffer is free again.
Whenwrite function is called with empty string or buffer, it doesnothing and waits for more input.
Class:http.Server#
- Extends:<net.Server>
Event:'checkContinue'#
request<http.IncomingMessage>response<http.ServerResponse>
Emitted each time a request with an HTTPExpect: 100-continue is received.If this event is not listened for, the server will automatically respondwith a100 Continue as appropriate.
Handling this event involves callingresponse.writeContinue() if theclient should continue to send the request body, or generating an appropriateHTTP response (e.g. 400 Bad Request) if the client should not continue to sendthe request body.
When this event is emitted and handled, the'request' event willnot be emitted.
Event:'checkExpectation'#
request<http.IncomingMessage>response<http.ServerResponse>
Emitted each time a request with an HTTPExpect header is received, where thevalue is not100-continue. If this event is not listened for, the server willautomatically respond with a417 Expectation Failed as appropriate.
When this event is emitted and handled, the'request' event willnot be emitted.
Event:'clientError'#
History
| Version | Changes |
|---|---|
| v12.0.0 | The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs. |
| v9.4.0 | The |
| v6.0.0 | The default action of calling |
| v0.1.94 | Added in: v0.1.94 |
exception<Error>socket<stream.Duplex>
If a client connection emits an'error' event, it will be forwarded here.Listener of this event is responsible for closing/destroying the underlyingsocket. For example, one may wish to more gracefully close the socket with acustom HTTP response instead of abruptly severing the connection. The socketmust be closed or destroyed before the listener ends.
This event is guaranteed to be passed an instance of the<net.Socket> class,a subclass of<stream.Duplex>, unless the user specifies a sockettype 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 headersof the current attachedhttp.ServerResponse has been sent, it isimmediately destroyed.
socket is thenet.Socket object that the error originated from.
import httpfrom'node: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);const http =require('node: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 norequest orresponseobject, so any HTTP response sent, including response headers and payload,must be written directly to thesocket object. Care must be taken toensure the response is a properly formatted HTTP response message.
err is an instance ofError with two extra columns:
bytesParsed: the bytes count of request packet that Node.js may have parsedcorrectly;rawPacket: the raw packet of current request.
In some cases, the client has already received the response and/or the sockethas already been destroyed, like in case ofECONNRESET errors. Beforetrying to send data to the socket, it is better to check that it is stillwritable.
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:'connect'#
request<http.IncomingMessage> Arguments for the HTTP request, as it is inthe'request'eventsocket<stream.Duplex> Network socket between the server and clienthead<Buffer> The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTPCONNECT method. If this event isnot listened for, then clients requesting aCONNECT method will have theirconnections 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 sockettype 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 datasent to the server on that socket.
Event:'connection'#
socket<stream.Duplex>
This event is emitted when a new TCP stream is established.socket istypically an object of typenet.Socket. Usually users will not want toaccess this event. In particular, the socket will not emit'readable' eventsbecause of how the protocol parser attaches to the socket. Thesocket canalso be accessed atrequest.socket.
This event can also be explicitly emitted by users to inject connectionsinto the HTTP server. In that case, anyDuplex stream can be passed.
Ifsocket.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 sockettype other than<net.Socket>.
Event:'dropRequest'#
request<http.IncomingMessage> Arguments for the HTTP request, as it is inthe'request'eventsocket<stream.Duplex> Network socket between the server and client
When the number of requests on a socket reaches the threshold ofserver.maxRequestsPerSocket, the server will drop new requestsand emit'dropRequest' event instead, then send503 to client.
Event:'request'#
request<http.IncomingMessage>response<http.ServerResponse>
Emitted each time there is a request. There may be multiple requestsper connection (in the case of HTTP Keep-Alive connections).
Event:'upgrade'#
History
| Version | Changes |
|---|---|
| v24.9.0 | Whether this event is fired can now be controlled by the |
| v10.0.0 | Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header. |
| v0.1.94 | Added in: v0.1.94 |
request<http.IncomingMessage> Arguments for the HTTP request, as it is inthe'request'eventsocket<stream.Duplex> Network socket between the server and clienthead<Buffer> The first packet of the upgraded stream (may be empty)
Emitted each time a client's HTTP upgrade request is accepted. By defaultall HTTP upgrade requests are ignored (i.e. only regular'request' eventsare emitted, sticking with the normal HTTP request/response flow) unless youlisten to this event, in which case they are all accepted (i.e. the'upgrade'event is emitted instead, and future communication must handled directlythrough the raw socket). You can control this more precisely by using theservershouldUpgradeCallback option.
Listening to this event is optional and clients cannot insist on a protocolchange.
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 datasent to the server on that socket.
If an upgrade is accepted byshouldUpgradeCallback but no event handleris registered then the socket is destroyed, resulting in an immediateconnection closure for the client.
This event is guaranteed to be passed an instance of the<net.Socket> class,a subclass of<stream.Duplex>, unless the user specifies a sockettype other than<net.Socket>.
server.close([callback])#
History
| Version | Changes |
|---|---|
| v19.0.0 | The method closes idle connections before returning. |
| v0.1.90 | Added in: v0.1.90 |
callback<Function>
Stops the server from accepting new connections and closes all connectionsconnected to this server which are not sending a request or waiting fora response.Seenet.Server.close().
const http =require('node:http');const server = http.createServer({keepAliveTimeout:60000 },(req, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);// Close the server after 10 secondssetTimeout(() => { server.close(() => {console.log('server on port 8000 closed successfully'); });},10000);server.closeAllConnections()#
Closes all established HTTP(S) connections connected to this server, includingactive connections connected to this server which are sending a request orwaiting for a response. This doesnot destroy sockets upgraded to a differentprotocol, such as WebSocket or HTTP/2.
This is a forceful way of closing all connections and should be used withcaution. Whenever using this in conjunction with
server.close, calling thisafterserver.closeis recommended as to avoid race conditions where newconnections are created between a call to this and a call toserver.close.
const http =require('node:http');const server = http.createServer({keepAliveTimeout:60000 },(req, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);// Close the server after 10 secondssetTimeout(() => { server.close(() => {console.log('server on port 8000 closed successfully'); });// Closes all connections, ensuring the server closes successfully server.closeAllConnections();},10000);server.closeIdleConnections()#
Closes all connections connected to this server which are not sending a requestor waiting for a response.
Starting with Node.js 19.0.0, there's no need for calling this method inconjunction with
server.closeto reapkeep-aliveconnections. Using itwon't cause any harm though, and it can be useful to ensure backwardscompatibility for libraries and applications that need to support versionsolder than 19.0.0. Whenever using this in conjunction withserver.close,calling thisafterserver.closeis recommended as to avoid raceconditions where new connections are created between a call to this and acall toserver.close.
const http =require('node:http');const server = http.createServer({keepAliveTimeout:60000 },(req, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);// Close the server after 10 secondssetTimeout(() => { server.close(() => {console.log('server on port 8000 closed successfully'); });// Closes idle connections, such as keep-alive connections. Server will close// once remaining active connections are terminated server.closeIdleConnections();},10000);server.headersTimeout#
History
| Version | Changes |
|---|---|
| v19.4.0, v18.14.0 | The default is now set to the minimum between 60000 (60 seconds) or |
| v11.3.0, v10.14.0 | Added in: v11.3.0, v10.14.0 |
- Type:<number>Default: The minimum between
server.requestTimeoutor60000.
Limit the amount of time the parser will wait to receive the complete HTTPheaders.
If the timeout expires, the server responds with status 408 withoutforwarding 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 againstpotential Denial-of-Service attacks in case the server is deployed without areverse proxy in front.
server.listen()#
Starts the HTTP server listening for connections.This method is identical toserver.listen() fromnet.Server.
server.listening#
- Type:<boolean> Indicates whether or not the server is listening for connections.
server.maxHeadersCount#
- Type:<number>Default:
2000
Limits maximum incoming headers count. If set to 0, no limit will be applied.
server.requestTimeout#
History
| Version | Changes |
|---|---|
| v18.0.0 | The default request timeout changed from no timeout to 300s (5 minutes). |
| v14.11.0 | Added in: v14.11.0 |
- Type:<number>Default:
300000
Sets the timeout value in milliseconds for receiving the entire request fromthe client.
If the timeout expires, the server responds with status 408 withoutforwarding 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 againstpotential Denial-of-Service attacks in case the server is deployed without areverse proxy in front.
server.setTimeout([msecs][, callback])#
History
| Version | Changes |
|---|---|
| v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
| v0.9.12 | Added in: v0.9.12 |
msecs<number>Default: 0 (no timeout)callback<Function>- Returns:<http.Server>
Sets the timeout value for sockets, and emits a'timeout' event onthe Server object, passing the socket as an argument, if a timeoutoccurs.
If there is a'timeout' event listener on the Server object, then itwill be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callbackis assigned to the Server's'timeout' event, timeouts must be handledexplicitly.
server.maxRequestsPerSocket#
- Type:<number> Requests per socket.Default: 0 (no limit)
The maximum number of requests socket can handlebefore closing keep alive connection.
A value of0 will disable the limit.
When the limit is reached it will set theConnection header value toclose,but will not actually close the connection, subsequent requests sentafter the limit is reached will get503 Service Unavailable as a response.
server.timeout#
History
| Version | Changes |
|---|---|
| v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
| v0.9.12 | Added in: v0.9.12 |
- Type:<number> Timeout in milliseconds.Default: 0 (no timeout)
The number of milliseconds of inactivity before a socket is presumedto have timed out.
A value of0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing thisvalue only affects new connections to the server, not any existing connections.
server.keepAliveTimeout#
- Type:<number> Timeout in milliseconds.Default:
5000(5 seconds).
The number of milliseconds of inactivity a server needs to wait for additionalincoming data, after it has finished writing the last response, before a socketwill be destroyed.
This timeout value is combined with theserver.keepAliveTimeoutBuffer option to determine the actual sockettimeout, calculated as:socketTimeout = keepAliveTimeout + keepAliveTimeoutBufferIf the server receives new data before the keep-alive timeout has fired, itwill reset the regular inactivity timeout, i.e.,server.timeout.
A value of0 will disable the keep-alive timeout behavior on incomingconnections.A value of0 makes the HTTP server behave similarly to Node.js versions priorto 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value onlyaffects new connections to the server, not any existing connections.
server.keepAliveTimeoutBuffer#
- Type:<number> Timeout in milliseconds.Default:
1000(1 second).
An additional buffer time added to theserver.keepAliveTimeout to extend the internal socket timeout.
This buffer helps reduce connection reset (ECONNRESET) errors by increasingthe socket timeout slightly beyond the advertised keep-alive timeout.
This option applies only to new incoming connections.
server[Symbol.asyncDispose]()#
History
| Version | Changes |
|---|---|
| v24.2.0 | No longer experimental. |
| v20.4.0 | Added in: v20.4.0 |
Callsserver.close() and returns a promise that fulfills when theserver has closed.
Class:http.ServerResponse#
- Extends:<http.OutgoingMessage>
This object is created internally by an HTTP server, not by the user. It ispassed as the second parameter to the'request' event.
Event:'close'#
Indicates that the response is completed, or its underlying connection wasterminated prematurely (before the response completion).
Event:'finish'#
Emitted when the response has been sent. More specifically, this event isemitted when the last segment of the response headers and body have beenhanded off to the operating system for transmission over the network. Itdoes not imply that the client has received anything yet.
response.addTrailers(headers)#
headers<Object>
This method adds HTTP trailing headers (a header but at the end of themessage) to the response.
Trailers willonly be emitted if chunked encoding is used for theresponse; if it is not (e.g. if the request was HTTP/1.0), they willbe silently discarded.
HTTP requires theTrailer header to be sent in order toemit 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 characterswill result in aTypeError being thrown.
response.connection#
response.socket.- Type:<stream.Duplex>
Seeresponse.socket.
response.end([data[, encoding]][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v10.0.0 | This method now returns a reference to |
| v0.1.90 | Added in: v0.1.90 |
data<string> |<Buffer> |<Uint8Array>encoding<string>callback<Function>- Returns:<this>
This method signals to the server that all of the response headers and bodyhave been sent; that server should consider this message complete.The method,response.end(), MUST be called on each response.
Ifdata is specified, it is similar in effect to callingresponse.write(data, encoding) followed byresponse.end(callback).
Ifcallback is specified, it will be called when the response streamis finished.
response.finished#
response.writableEnded.- Type:<boolean>
Theresponse.finished property will betrue ifresponse.end()has been called.
response.flushHeaders()#
Flushes the response headers. See also:request.flushHeaders().
response.getHeader(name)#
name<string>- Returns:<number> |<string> |<string[]> |<undefined>
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 dependson the arguments provided toresponse.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 numberconst setCookie = response.getHeader('set-cookie');// setCookie is of type string[]response.getHeaderNames()#
- Returns:<string[]>
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()#
- Returns:<Object>
Returns a shallow copy of the current outgoing headers. Since a shallow copyis used, array values may be mutated without additional calls to variousheader-related http module methods. The keys of the returned object are theheader names and the values are the respective header values. All header namesare lowercase.
The object returned by theresponse.getHeaders() methoddoes notprototypically inherit from the JavaScriptObject. This means that typicalObject methods such asobj.toString(),obj.hasOwnProperty(), and othersare not defined andwill 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)#
Returnstrue if the header identified byname is currently set in theoutgoing headers. The header name matching is case-insensitive.
const hasContentType = response.hasHeader('content-type');response.headersSent#
- Type:<boolean>
Boolean (read-only). True if headers were sent, false otherwise.
response.removeHeader(name)#
name<string>
Removes a header that's queued for implicit sending.
response.removeHeader('Content-Encoding');response.sendDate#
- Type:<boolean>
When true, the Date header will be automatically generated and sent inthe response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date headerin responses.
response.setHeader(name, value)#
name<string>value<number> |<string> |<string[]>- Returns:<http.ServerResponse>
Returns the response object.
Sets a single header value for implicit headers. If this header already existsin the to-be-sent headers, its value will be replaced. Use an array of stringshere to send multiple headers with the same name. Non-string values will bestored without modification. Therefore,response.getHeader() may returnnon-string values. However, the non-string values will be converted to stringsfor 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 characterswill result in aTypeError being thrown.
When headers have been set withresponse.setHeader(), they will be mergedwith any headers passed toresponse.writeHead(), with the headers passedtoresponse.writeHead() given precedence.
// Returns content-type = text/plainconst 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');});Ifresponse.writeHead() method is called and this method has not beencalled, it will directly write the supplied header values onto the networkchannel without caching internally, and theresponse.getHeader() on theheader will not yield the expected result. If progressive population of headersis desired with potential future retrieval and modification, useresponse.setHeader() instead ofresponse.writeHead().
response.setTimeout(msecs[, callback])#
msecs<number>callback<Function>- Returns:<http.ServerResponse>
Sets the Socket's timeout value tomsecs. If a callback isprovided, then it is added as a listener on the'timeout' event onthe response object.
If no'timeout' listener is added to the request, the response, orthe server, then sockets are destroyed when they time out. If a handler isassigned to the request, the response, or the server's'timeout' events,timed out sockets must be handled explicitly.
response.socket#
- Type:<stream.Duplex>
Reference to the underlying socket. Usually users will not want to accessthis property. In particular, the socket will not emit'readable' eventsbecause of how the protocol parser attaches to the socket. Afterresponse.end(), the property is nulled.
import httpfrom'node:http';const server = http.createServer((req, res) => {const ip = res.socket.remoteAddress;const port = res.socket.remotePort; res.end(`Your IP address is${ip} and your source port is${port}.`);}).listen(3000);const http =require('node:http');const server = http.createServer((req, res) => {const ip = res.socket.remoteAddress;const port = res.socket.remotePort; res.end(`Your IP address is${ip} and your source port is${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 sockettype other than<net.Socket>.
response.statusCode#
- Type:<number>Default:
200
When using implicit headers (not callingresponse.writeHead() explicitly),this property controls the status code that will be sent to the client whenthe headers get flushed.
response.statusCode =404;After response header was sent to the client, this property indicates thestatus code which was sent out.
response.statusMessage#
- Type:<string>
When using implicit headers (not callingresponse.writeHead() explicitly),this property controls the status message that will be sent to the client whenthe headers get flushed. If this is left asundefined then the standardmessage for the status code will be used.
response.statusMessage ='Not found';After response header was sent to the client, this property indicates thestatus message which was sent out.
response.strictContentLength#
- Type:<boolean>Default:
false
If set totrue, Node.js will check whether theContent-Lengthheader value and the size of the body, in bytes, are equal.Mismatching theContent-Length header value will resultin anError being thrown, identified bycode:'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
response.writableEnded#
- Type:<boolean>
Istrue afterresponse.end() has been called. This propertydoes not indicate whether the data has been flushed, for this useresponse.writableFinished instead.
response.writableFinished#
- Type:<boolean>
Istrue if all data has been flushed to the underlying system, immediatelybefore the'finish' event is emitted.
response.write(chunk[, encoding][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v0.1.29 | Added in: v0.1.29 |
chunk<string> |<Buffer> |<Uint8Array>encoding<string>Default:'utf8'callback<Function>- Returns:<boolean>
If this method is called andresponse.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 maybe called multiple times to provide successive parts of the body.
IfrejectNonStandardBodyWrites is set to true increateServerthen writing to the body is not allowed when the request method or responsestatus do not support content. If an attempt is made to write to the body for aHEAD request or as part of a204 or304response, a synchronousErrorwith the codeERR_HTTP_BODY_NOT_ALLOWED is thrown.
chunk can be a string or a buffer. Ifchunk 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-partbody encodings that may be used.
The first timeresponse.write() is called, it will send the bufferedheader information and the first chunk of the body to the client. The secondtimeresponse.write() is called, Node.js assumes data will be streamed,and sends the new data separately. That is, the response is buffered up to thefirst chunk of the body.
Returnstrue if the entire data was flushed successfully to the kernelbuffer. Returnsfalse if all or part of the data was queued in user memory.'drain' will be emitted when the buffer is free again.
response.writeContinue()#
Sends an HTTP/1.1 100 Continue message to the client, indicating thatthe request body should be sent. See the'checkContinue' event onServer.
response.writeEarlyHints(hints[, callback])#
History
| Version | Changes |
|---|---|
| v18.11.0 | Allow passing hints as an object. |
| v18.11.0 | Added in: v18.11.0 |
hints<Object>callback<Function>
Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,indicating that the user agent can preload/preconnect the linked resources.Thehints is an object containing the values of headers to be sent withearly hints message. The optionalcallback argument will be called whenthe response message has been written.
Example
const earlyHintsLink ='</styles.css>; rel=preload; as=style';response.writeEarlyHints({'link': earlyHintsLink,});const earlyHintsLinks = ['</styles.css>; rel=preload; as=style','</scripts.js>; rel=preload; as=script',];response.writeEarlyHints({'link': earlyHintsLinks,'x-trace-id':'id for diagnostics',});constearlyHintsCallback = () =>console.log('early hints message sent');response.writeEarlyHints({'link': earlyHintsLinks,}, earlyHintsCallback);response.writeHead(statusCode[, statusMessage][, headers])#
History
| Version | Changes |
|---|---|
| v14.14.0 | Allow passing headers as an array. |
| v11.10.0, v10.17.0 | Return |
| v5.11.0, v4.4.5 | A |
| v0.1.30 | Added in: v0.1.30 |
statusCode<number>statusMessage<string>headers<Object> |<Array>- Returns:<http.ServerResponse>
Sends a response header to the request. The status code is a 3-digit HTTPstatus code, like404. The last argument,headers, are the response headers.Optionally one can give a human-readablestatusMessage as the secondargument.
headers may be anArray where the keys and values are in the same list.It isnot 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 sameformat asrequest.rawHeaders.
Returns a reference to theServerResponse, 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 mustbe called beforeresponse.end() is called.
Ifresponse.write() orresponse.end() are called before callingthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set withresponse.setHeader(), they will be mergedwith any headers passed toresponse.writeHead(), with the headers passedtoresponse.writeHead() given precedence.
If this method is called andresponse.setHeader() has not been called,it will directly write the supplied header values onto the network channelwithout caching internally, and theresponse.getHeader() on the headerwill not yield the expected result. If progressive population of headers isdesired with potential future retrieval and modification, useresponse.setHeader() instead.
// Returns content-type = text/plainconst 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 read in bytes, not characters. UseBuffer.byteLength() to determine the length of the body in bytes. Node.jswill check whetherContent-Length and the length of the body which hasbeen transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characterswill result in aTypeError being thrown.
response.writeProcessing()#
Sends a HTTP/1.1 102 Processing message to the client, indicating thatthe request body should be sent.
Class:http.IncomingMessage#
History
| Version | Changes |
|---|---|
| v15.5.0 | The |
| v13.1.0, v12.16.0 | The |
| v0.1.17 | Added in: v0.1.17 |
- Extends:<stream.Readable>
AnIncomingMessage object is created byhttp.Server orhttp.ClientRequest and passed as the first argument to the'request'and'response' event respectively. It may be used to access responsestatus, headers, and data.
Different from itssocket value which is a subclass of<stream.Duplex>, theIncomingMessage itself extends<stream.Readable> and is created separately toparse and emit the incoming HTTP headers and payload, as the underlying socketmay be reused multiple times in case of keep-alive.
Event:'aborted'#
'close' event instead.Emitted when the request has been aborted.
Event:'close'#
History
| Version | Changes |
|---|---|
| v16.0.0 | The close event is now emitted when the request has been completed and not when the underlying socket is closed. |
| v0.4.2 | Added in: v0.4.2 |
Emitted when the request has been completed.
message.aborted#
- Type:<boolean>
Themessage.aborted property will betrue if the request hasbeen aborted.
message.complete#
- Type:<boolean>
Themessage.complete property will betrue if a complete HTTP message hasbeen received and successfully parsed.
This property is particularly useful as a means of determining if a client orserver 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#
message.socket.Alias formessage.socket.
message.destroy([error])#
History
| Version | Changes |
|---|---|
| v14.5.0, v12.19.0 | The function returns |
| v0.3.0 | Added in: v0.3.0 |
Callsdestroy() on the socket that received theIncomingMessage. Iferroris provided, an'error' event is emitted on the socket anderror is passedas an argument to any listeners on the event.
message.headers#
History
| Version | Changes |
|---|---|
| v19.5.0, v18.14.0 | The |
| v15.1.0 |
|
| v0.1.5 | Added in: v0.1.5 |
- Type:<Object>
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 theheader name:
- Duplicates of
age,authorization,content-length,content-type,etag,expires,from,host,if-modified-since,if-unmodified-since,last-modified,location,max-forwards,proxy-authorization,referer,retry-after,server, oruser-agentare discarded.To allow duplicate values of the headers listed above to be joined,use the optionjoinDuplicateHeadersinhttp.request()andhttp.createServer(). See RFC 9110 Section 5.3 for moreinformation. set-cookieis always an array. Duplicates are added to the array.- For duplicate
cookieheaders, the values are joined together with;. - For all other headers, the values are joined together with
,.
message.headersDistinct#
- Type:<Object>
Similar tomessage.headers, but there is no join logic and the values arealways arrays of strings, even for headers received just once.
// Prints something like://// { 'user-agent': ['curl/7.22.0'],// host: ['127.0.0.1:8000'],// accept: ['*/*'] }console.log(request.headersDistinct);message.httpVersion#
- Type:<string>
In case of server request, the HTTP version sent by the client. In the case ofclient response, the HTTP version of the connected-to server.Probably either'1.1' or'1.0'.
Alsomessage.httpVersionMajor is the first integer andmessage.httpVersionMinor is the second.
message.method#
- Type:<string>
Only valid for request obtained fromhttp.Server.
The request method as a string. Read only. Examples:'GET','DELETE'.
message.rawHeaders#
- Type:<string[]>
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It isnot alist of tuples. So, the even-numbered offsets are key values, and theodd-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#
- Type:<string[]>
The raw request/response trailer keys and values exactly as they werereceived. Only populated at the'end' event.
message.setTimeout(msecs[, callback])#
msecs<number>callback<Function>- Returns:<http.IncomingMessage>
Callsmessage.socket.setTimeout(msecs, callback).
message.socket#
- Type:<stream.Duplex>
Thenet.Socket object associated with the connection.
With HTTPS support, userequest.socket.getPeerCertificate() to obtain theclient'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 sockettype other than<net.Socket> or internally nulled.
message.statusCode#
- Type:<number>
Only valid for response obtained fromhttp.ClientRequest.
The 3-digit HTTP response status code. E.G.404.
message.statusMessage#
- Type:<string>
Only valid for response obtained fromhttp.ClientRequest.
The HTTP response status message (reason phrase). E.G.OK orInternal Server Error.
message.trailers#
- Type:<Object>
The request/response trailers object. Only populated at the'end' event.
message.trailersDistinct#
- Type:<Object>
Similar tomessage.trailers, but there is no join logic and the values arealways arrays of strings, even for headers received just once.Only populated at the'end' event.
message.url#
- Type:<string>
Only valid for request obtained fromhttp.Server.
Request URL string. This contains only the URL that is present in the actualHTTP request. Take the following request:
GET/status?name=ryanHTTP/1.1Accept:text/plainTo parse the URL into its parts:
newURL(`http://${process.env.HOST ??'localhost'}${request.url}`);Whenrequest.url is'/status?name=ryan' andprocess.env.HOST is undefined:
$node>new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);URL { href: 'http://localhost/status?name=ryan', origin: 'http://localhost', protocol: 'http:', username: '', password: '', host: 'localhost', hostname: 'localhost', port: '', pathname: '/status', search: '?name=ryan', searchParams: URLSearchParams { 'name' => 'ryan' }, hash: ''}Ensure that you setprocess.env.HOST to the server's host name, or considerreplacing this part entirely. If usingreq.headers.host, ensure propervalidation is used, as clients may specify a customHost header.
Class:http.OutgoingMessage#
- Extends:<Stream>
This class serves as the parent class ofhttp.ClientRequestandhttp.ServerResponse. It is an abstract outgoing message fromthe perspective of the participants of an HTTP transaction.
Event:'prefinish'#
Emitted afteroutgoingMessage.end() is called.When the event is emitted, all data has been processed but not necessarilycompletely flushed.
outgoingMessage.addTrailers(headers)#
headers<Object>
Adds HTTP trailers (headers but at the end of the message) to the message.
Trailers willonly be emitted if the message is chunked encoded. If not,the trailers will be silently discarded.
HTTP requires theTrailer header to be sent to emit trailers,with a list of header field names 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 characterswill result in aTypeError being thrown.
outgoingMessage.appendHeader(name, value)#
name<string> Header namevalue<string> |<string[]> Header value- Returns:<this>
Append a single header value to the header object.
If the value is an array, this is equivalent to calling this method multipletimes.
If there were no previous values for the header, this is equivalent to callingoutgoingMessage.setHeader(name, value).
Depending of the value ofoptions.uniqueHeaders when the client request or theserver were created, this will end up in the header being sent multiple times ora single time with values joined using;.
outgoingMessage.connection#
outgoingMessage.socket instead.Alias ofoutgoingMessage.socket.
outgoingMessage.destroy([error])#
Destroys the message. Once a socket is associated with the messageand is connected, that socket will be destroyed as well.
outgoingMessage.end(chunk[, encoding][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v0.11.6 | add |
| v0.1.90 | Added in: v0.1.90 |
chunk<string> |<Buffer> |<Uint8Array>encoding<string> Optional,Default:utf8callback<Function> Optional- Returns:<this>
Finishes the outgoing message. If any parts of the body are unsent, it willflush them to the underlying system. If the message is chunked, it willsend the terminating chunk0\r\n\r\n, and send the trailers (if any).
Ifchunk is specified, it is equivalent to callingoutgoingMessage.write(chunk, encoding), followed byoutgoingMessage.end(callback).
Ifcallback is provided, it will be called when the message is finished(equivalent to a listener of the'finish' event).
outgoingMessage.flushHeaders()#
Flushes the message headers.
For efficiency reason, Node.js normally buffers the message headersuntiloutgoingMessage.end() is called or the first chunk of message datais written. It then tries to pack the headers and data into a single TCPpacket.
It is usually desired (it saves a TCP round-trip), but not when the firstdata is not sent until possibly much later.outgoingMessage.flushHeaders()bypasses the optimization and kickstarts the message.
outgoingMessage.getHeader(name)#
name<string> Name of header- Returns:<number> |<string> |<string[]> |<undefined>
Gets the value of the HTTP header with the given name. If that header is notset, the returned value will beundefined.
outgoingMessage.getHeaderNames()#
- Returns:<string[]>
Returns an array containing the unique names of the current outgoing headers.All names are lowercase.
outgoingMessage.getHeaders()#
- Returns:<Object>
Returns a shallow copy of the current outgoing headers. Since a shallowcopy is used, array values may be mutated without additional calls tovarious header-related HTTP module methods. The keys of the returnedobject are the header names and the values are the respective headervalues. All header names are lowercase.
The object returned by theoutgoingMessage.getHeaders() method doesnot prototypically inherit from the JavaScriptObject. This means thattypicalObject methods such asobj.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)#
Returnstrue if the header identified byname is currently set in theoutgoing headers. The header name is case-insensitive.
const hasContentType = outgoingMessage.hasHeader('content-type');outgoingMessage.headersSent#
- Type:<boolean>
Read-only.true if the headers were sent, otherwisefalse.
outgoingMessage.pipe()#
Overrides thestream.pipe() method inherited from the legacyStream classwhich is the parent class ofhttp.OutgoingMessage.
Calling this method will throw anError becauseoutgoingMessage is awrite-only stream.
outgoingMessage.removeHeader(name)#
name<string> Header name
Removes a header that is queued for implicit sending.
outgoingMessage.removeHeader('Content-Encoding');outgoingMessage.setHeader(name, value)#
name<string> Header namevalue<number> |<string> |<string[]> Header value- Returns:<this>
Sets a single header value. If the header already exists in the to-be-sentheaders, its value will be replaced. Use an array of strings to send multipleheaders with the same name.
outgoingMessage.setHeaders(headers)#
Sets multiple header values for implicit headers.headers must be an instance ofHeaders orMap,if a header already exists in the to-be-sent headers,its value will be replaced.
const headers =newHeaders({foo:'bar' });outgoingMessage.setHeaders(headers);or
const headers =newMap([['foo','bar']]);outgoingMessage.setHeaders(headers);When headers have been set withoutgoingMessage.setHeaders(),they will be merged with any headers passed toresponse.writeHead(),with the headers passed toresponse.writeHead() given precedence.
// Returns content-type = text/plainconst server = http.createServer((req, res) => {const headers =newHeaders({'Content-Type':'text/html' }); res.setHeaders(headers); res.writeHead(200, {'Content-Type':'text/plain' }); res.end('ok');});outgoingMessage.setTimeout(msecs[, callback])#
msecs<number>callback<Function> Optional function to be called when a timeoutoccurs. Same as binding to thetimeoutevent.- Returns:<this>
Once a socket is associated with the message and is connected,socket.setTimeout() will be called withmsecs as the first parameter.
outgoingMessage.socket#
- Type:<stream.Duplex>
Reference to the underlying socket. Usually, users will not want to accessthis property.
After callingoutgoingMessage.end(), this property will be nulled.
outgoingMessage.writableCorked#
- Type:<number>
The number of timesoutgoingMessage.cork() has been called.
outgoingMessage.writableEnded#
- Type:<boolean>
Istrue ifoutgoingMessage.end() has been called. This property doesnot indicate whether the data has been flushed. For that purpose, usemessage.writableFinished instead.
outgoingMessage.writableFinished#
- Type:<boolean>
Istrue if all data has been flushed to the underlying system.
outgoingMessage.writableHighWaterMark#
- Type:<number>
ThehighWaterMark of the underlying socket if assigned. Otherwise, the defaultbuffer level whenwritable.write() starts returning false (16384).
outgoingMessage.write(chunk[, encoding][, callback])#
History
| Version | Changes |
|---|---|
| v15.0.0 | The |
| v0.11.6 | The |
| v0.1.29 | Added in: v0.1.29 |
chunk<string> |<Buffer> |<Uint8Array>encoding<string>Default:utf8callback<Function>- Returns:<boolean>
Sends a chunk of the body. This method can be called multiple times.
Theencoding argument is only relevant whenchunk is a string. Defaults to'utf8'.
Thecallback argument is optional and will be called when this chunk of datais flushed.
Returnstrue if the entire data was flushed successfully to the kernelbuffer. Returnsfalse if all or part of the data was queued in the usermemory. The'drain' event will be emitted when the buffer is free again.
http.METHODS#
- Type:<string[]>
A list of the HTTP methods that are supported by the parser.
http.STATUS_CODES#
- Type:<Object>
A collection of all the standard HTTP response status codes, and theshort description of each. For example,http.STATUS_CODES[404] === 'Not Found'.
http.createServer([options][, requestListener])#
History
| Version | Changes |
|---|---|
| v25.1.0 | Add optimizeEmptyRequests option. |
| v24.9.0 | The |
| v20.1.0, v18.17.0 | The |
| v18.0.0 | The |
| v18.0.0 | The |
| v17.7.0, v16.15.0 | The |
| v13.3.0 | The |
| v13.8.0, v12.15.0, v10.19.0 | The |
| v9.6.0, v8.12.0 | The |
| v0.1.13 | Added in: v0.1.13 |
options<Object>connectionsCheckingInterval: Sets the interval value in milliseconds tocheck for request and headers timeout in incomplete requests.Default:30000.headersTimeout: Sets the timeout value in milliseconds for receivingthe complete HTTP headers from the client.Seeserver.headersTimeoutfor more information.Default:60000.highWaterMark<number> Optionally overrides allsockets'readableHighWaterMarkandwritableHighWaterMark. This affectshighWaterMarkproperty of bothIncomingMessageandServerResponse.Default: Seestream.getDefaultHighWaterMark().insecureHTTPParser<boolean> If set totrue, it will use a HTTP parserwith leniency flags enabled. Using the insecure parser should be avoided.See--insecure-http-parserfor more information.Default:false.IncomingMessage<http.IncomingMessage> Specifies theIncomingMessageclass to be used. Useful for extending the originalIncomingMessage.Default:IncomingMessage.joinDuplicateHeaders<boolean> If set totrue, this option allowsjoining the field line values of multiple headers in a request witha comma (,) instead of discarding the duplicates.For more information, refer tomessage.headers.Default:false.keepAlive<boolean> If set totrue, it enables keep-alive functionalityon the socket immediately after a new incoming connection is received,similarly on what is done in [socket.setKeepAlive([enable][, initialDelay])][socket.setKeepAlive(enable, initialDelay)].Default:false.keepAliveInitialDelay<number> If set to a positive number, it sets theinitial delay before the first keepalive probe is sent on an idle socket.Default:0.keepAliveTimeout: The number of milliseconds of inactivity a serverneeds to wait for additional incoming data, after it has finished writingthe last response, before a socket will be destroyed.Seeserver.keepAliveTimeoutfor more information.Default:5000.maxHeaderSize<number> Optionally overrides the value of--max-http-header-sizefor requests received by this server, i.e.the maximum length of request headers in bytes.Default: 16384 (16 KiB).noDelay<boolean> If set totrue, it disables the use of Nagle'salgorithm immediately after a new incoming connection is received.Default:true.requestTimeout: Sets the timeout value in milliseconds for receivingthe entire request from the client.Seeserver.requestTimeoutfor more information.Default:300000.requireHostHeader<boolean> If set totrue, it forces the server torespond with a 400 (Bad Request) status code to any HTTP/1.1request message that lacks a Host header(as mandated by the specification).Default:true.ServerResponse<http.ServerResponse> Specifies theServerResponseclassto be used. Useful for extending the originalServerResponse.Default:ServerResponse.shouldUpgradeCallback(request)<Function> A callback which receives anincoming request and returns a boolean, to control which upgrade attemptsshould be accepted. Accepted upgrades will fire an'upgrade'event (ortheir sockets will be destroyed, if no listener is registered) whilerejected upgrades will fire a'request'event like any non-upgraderequest. This options defaults to() => server.listenerCount('upgrade') > 0.uniqueHeaders<Array> A list of response headers that should be sent onlyonce. If the header's value is an array, the items will be joinedusing;.rejectNonStandardBodyWrites<boolean> If set totrue, an error is thrownwhen writing to an HTTP response which does not have a body.Default:false.optimizeEmptyRequests<boolean> If set totrue, requests withoutContent-LengthorTransfer-Encodingheaders (indicating no body) will be initialized with analready-ended body stream, so they will never emit any stream events(like'data'or'end'). You can usereq.readableEndedto detect this case.Default:false.
requestListener<Function>Returns:<http.Server>
Returns a new instance ofhttp.Server.
TherequestListener is a function which is automaticallyadded to the'request' event.
import httpfrom'node:http';// Create a local server to receive data fromconst 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('node:http');// Create a local server to receive data fromconst server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);
import httpfrom'node:http';// Create a local server to receive data fromconst server = http.createServer();// Listen to the request eventserver.on('request',(request, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);const http =require('node:http');// Create a local server to receive data fromconst server = http.createServer();// Listen to the request eventserver.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])#
History
| Version | Changes |
|---|---|
| v10.9.0 | The |
| v7.5.0 | The |
| v0.3.6 | Added in: v0.3.6 |
url<string> |<URL>options<Object> Accepts the sameoptionsashttp.request(), with the method set to GET by default.callback<Function>- Returns:<http.ClientRequest>
Since most requests are GET requests without bodies, Node.js provides thisconvenience method. The only difference between this method andhttp.request() is that it sets the method to GET by default and callsreq.end()automatically. The callback must take care to consume the responsedata for reasons stated inhttp.ClientRequest section.
Thecallback 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 =newError('Request Failed.\n' +`Status Code:${statusCode}`); }elseif (!/^application\/json/.test(contentType)) { error =newError('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 fromconst server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type':'application/json' }); res.end(JSON.stringify({data:'Hello World!', }));});server.listen(8000);http.globalAgent#
History
| Version | Changes |
|---|---|
| v19.0.0 | The agent now uses HTTP Keep-Alive and a 5 second timeout by default. |
| v0.5.9 | Added in: v0.5.9 |
- Type:<http.Agent>
Global instance ofAgent which is used as the default for all HTTP clientrequests. Diverges from a defaultAgent configuration by havingkeepAliveenabled and atimeout of 5 seconds.
http.maxHeaderSize#
- Type:<number>
Read-only property specifying the maximum allowed size of HTTP headers in bytes.Defaults to 16 KiB. Configurable using the--max-http-header-size CLIoption.
This can be overridden for servers and client requests by passing themaxHeaderSize option.
http.request(options[, callback])#
http.request(url[, options][, callback])#
History
| Version | Changes |
|---|---|
| v16.7.0, v14.18.0 | When using a |
| v15.3.0, v14.17.0 | It is possible to abort a request with an AbortSignal. |
| v13.3.0 | The |
| v13.8.0, v12.15.0, v10.19.0 | The |
| v10.9.0 | The |
| v7.5.0 | The |
| v0.3.6 | Added in: v0.3.6 |
url<string> |<URL>options<Object>agent<http.Agent> |<boolean> ControlsAgentbehavior. Possiblevalues:undefined(default): usehttp.globalAgentfor this host and port.Agentobject: explicitly use the passed inAgent.false: causes a newAgentwith default values to be used.
auth<string> Basic authentication ('user:password') to compute anAuthorization header.createConnection<Function> A function that produces a socket/stream touse for the request when theagentoption is not used. This can be used toavoid creating a customAgentclass just to override the defaultcreateConnectionfunction. Seeagent.createConnection()for moredetails. AnyDuplexstream is a valid return value.defaultPort<number> Default port for the protocol.Default:agent.defaultPortif anAgentis used, elseundefined.family<number> IP address family to use when resolvinghostorhostname. Valid values are4or6. When unspecified, both IP v4 andv6 will be used.headers<Object> |<Array> An object or an array of strings containing requestheaders. The array is in the same format asmessage.rawHeaders.hints<number> Optionaldns.lookup()hints.host<string> A domain name or IP address of the server to issue therequest to.Default:'localhost'.hostname<string> Alias forhost. To supporturl.parse(),hostnamewill be used if bothhostandhostnameare specified.insecureHTTPParser<boolean> If set totrue, it will use a HTTP parserwith leniency flags enabled. Using the insecure parser should be avoided.See--insecure-http-parserfor more information.Default:falsejoinDuplicateHeaders<boolean> It joins the field line values ofmultiple headers in a request with,instead of discardingthe duplicates. Seemessage.headersfor more information.Default:false.localAddress<string> Local interface to bind for network connections.localPort<number> Local port to connect from.lookup<Function> Custom lookup function.Default:dns.lookup().maxHeaderSize<number> Optionally overrides the value of--max-http-header-size(the maximum length of response headers inbytes) for responses received from the server.Default: 16384 (16 KiB).method<string> A string specifying the HTTP request method.Default:'GET'.path<string> Request path. Should include query string if any.E.G.'/index.html?page=12'. An exception is thrown when the request pathcontains illegal characters. Currently, only spaces are rejected but thatmay change in the future.Default:'/'.port<number> Port of remote server.Default:defaultPortif set,else80.protocol<string> Protocol to use.Default:'http:'.setDefaultHeaders<boolean>: Specifies whether or not to automatically adddefault headers such asConnection,Content-Length,Transfer-Encoding,andHost. If set tofalsethen all necessary headers must be addedmanually. Defaults totrue.setHost<boolean>: Specifies whether or not to automatically add theHostheader. If provided, this overridessetDefaultHeaders. Defaults totrue.signal<AbortSignal>: An AbortSignal that may be used to abort an ongoingrequest.socketPath<string> Unix domain socket. Cannot be used if one ofhostorportis specified, as those specify a TCP Socket.timeout<number>: A number specifying the socket timeout in milliseconds.This will set the timeout before the socket is connected.uniqueHeaders<Array> A list of request headers that should be sentonly once. If the header's value is an array, the items will be joinedusing;.
callback<Function>- Returns:<http.ClientRequest>
options insocket.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 aURL object. Ifurl is astring, it is automatically parsed withnew URL(). If it is aURLobject, it will be automatically converted to an ordinaryoptions object.
If bothurl andoptions are specified, the objects are merged, with theoptions properties taking precedence.
The optionalcallback parameter will be added as a one-time listener forthe'response' event.
http.request() returns an instance of thehttp.ClientRequestclass. TheClientRequest instance is a writable stream. If one needs toupload a file with a POST request, then write to theClientRequest object.
import httpfrom'node:http';import {Buffer }from'node:buffer';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 bodyreq.write(postData);req.end();const http =require('node: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 bodyreq.write(postData);req.end();
In the examplereq.end() was called. Withhttp.request() onemust always callreq.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 emittedon the returned request object. As with all'error' events, if no listenersare registered the error will be thrown.
There are a few special headers that should be noted.
Sending a 'Connection: keep-alive' will notify Node.js that the connection tothe server should be persisted until the next request.
Sending a 'Content-Length' header will disable the default chunked encoding.
Sending an 'Expect' header will immediately send the request headers.Usually, when sending 'Expect: 100-continue', both a timeout and a listenerfor the
'continue'event should be set. See RFC 2616 Section 8.2.3 for moreinformation.Sending an Authorization header will override using the
authoptionto compute basic authentication.
Example using aURL asoptions:
const options =newURL('http://abc:xyz@example.com');const req = http.request(options,(res) => {// ...});In a successful request, the following events will be emitted in the followingorder:
'socket''response''data'any number of times, on theresobject('data'will not be emitted at all if the response body is empty, forinstance, in most redirects)'end'on theresobject
'close'
In the case of a connection error, the following events will be emitted:
'socket''error''close'
In the case of a premature connection close before the response is received,the following events will be emitted in the following order:
'socket''error'with an error with message'Error: socket hang up'and code'ECONNRESET''close'
In the case of a premature connection close after the response is received,the following events will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (connection closed here)
'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET''close'on theresobject
Ifreq.destroy() is called before a socket is assigned, the followingevents will be emitted in the following order:
- (
req.destroy()called here) 'error'with an error with message'Error: socket hang up'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'
Ifreq.destroy() is called before the connection succeeds, the followingevents will be emitted in the following order:
'socket'- (
req.destroy()called here) 'error'with an error with message'Error: socket hang up'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'
Ifreq.destroy() is called after the response is received, the followingevents will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (
req.destroy()called here) 'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'on theresobject
Ifreq.abort() is called before a socket is assigned, the followingevents will be emitted in the following order:
- (
req.abort()called here) 'abort''close'
Ifreq.abort() is called before the connection succeeds, the followingevents will be emitted in the following order:
'socket'- (
req.abort()called here) 'abort''error'with an error with message'Error: socket hang up'and code'ECONNRESET''close'
Ifreq.abort() is called after the response is received, the followingevents will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (
req.abort()called here) 'abort''aborted'on theresobject'error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET'.'close''close'on theresobject
Setting thetimeout option or using thesetTimeout() function willnot abort the request or do anything besides add a'timeout' event.
Passing anAbortSignal and then callingabort() on the correspondingAbortController will behave the same way as calling.destroy() on therequest. Specifically, the'error' event will be emitted with an error withthe message'AbortError: The operation was aborted', the code'ABORT_ERR'and thecause, if one was provided.
http.validateHeaderName(name[, label])#
History
| Version | Changes |
|---|---|
| v19.5.0, v18.14.0 | The |
| v14.3.0 | Added in: v14.3.0 |
Performs the low-level validations on the providedname that are done whenres.setHeader(name, value) is called.
Passing illegal value asname will result in aTypeError being thrown,identified bycode: 'ERR_INVALID_HTTP_TOKEN'.
It is not necessary to use this method before passing headers to an HTTP requestor response. The HTTP module will automatically validate such headers.
Example:
import { validateHeaderName }from'node:http';try {validateHeaderName('');}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code);// --> 'ERR_INVALID_HTTP_TOKEN'console.error(err.message);// --> 'Header name must be a valid HTTP token [""]'}const { validateHeaderName } =require('node:http');try {validateHeaderName('');}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code);// --> 'ERR_INVALID_HTTP_TOKEN'console.error(err.message);// --> 'Header name must be a valid HTTP token [""]'}
http.validateHeaderValue(name, value)#
Performs the low-level validations on the providedvalue that are done whenres.setHeader(name, value) is called.
Passing illegal value asvalue will result in aTypeError being thrown.
- Undefined value error is identified by
code: 'ERR_HTTP_INVALID_HEADER_VALUE'. - Invalid value character error is identified by
code: 'ERR_INVALID_CHAR'.
It is not necessary to use this method before passing headers to an HTTP requestor response. The HTTP module will automatically validate such headers.
Examples:
import { validateHeaderValue }from'node:http';try {validateHeaderValue('x-my-header',undefined);}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code ==='ERR_HTTP_INVALID_HEADER_VALUE');// --> trueconsole.error(err.message);// --> 'Invalid value "undefined" for header "x-my-header"'}try {validateHeaderValue('x-my-header','oʊmɪɡə');}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code ==='ERR_INVALID_CHAR');// --> trueconsole.error(err.message);// --> 'Invalid character in header content ["x-my-header"]'}const { validateHeaderValue } =require('node:http');try {validateHeaderValue('x-my-header',undefined);}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code ==='ERR_HTTP_INVALID_HEADER_VALUE');// --> trueconsole.error(err.message);// --> 'Invalid value "undefined" for header "x-my-header"'}try {validateHeaderValue('x-my-header','oʊmɪɡə');}catch (err) {console.error(errinstanceofTypeError);// --> trueconsole.error(err.code ==='ERR_INVALID_CHAR');// --> trueconsole.error(err.message);// --> 'Invalid character in header content ["x-my-header"]'}
http.setMaxIdleHTTPParsers(max)#
max<number>Default:1000.
Set the maximum number of idle HTTP parsers.
Class:WebSocket#
A browser-compatible implementation of<WebSocket>.
Built-in Proxy Support#
When Node.js creates the global agent, if theNODE_USE_ENV_PROXY environment variable isset to1 or--use-env-proxy is enabled, the global agent will be constructedwithproxyEnv: process.env, enabling proxy support based on the environment variables.Custom agents can also be created with proxy support by passing aproxyEnv option when constructing the agent. The value can beprocess.envif they just want to inherit the configuration from the environment variables,or an object with specific setting overriding the environment.
The following properties of theproxyEnv are checked to configure proxysupport.
HTTP_PROXYorhttp_proxy: Proxy server URL for HTTP requests. If both are set,http_proxytakes precedence.HTTPS_PROXYorhttps_proxy: Proxy server URL for HTTPS requests. If both are set,https_proxytakes precedence.NO_PROXYorno_proxy: Comma-separated list of hosts to bypass the proxy. If both are set,no_proxytakes precedence.
If the request is made to a Unix domain socket, the proxy settings will be ignored.
Proxy URL Format#
Proxy URLs can use either HTTP or HTTPS protocols:
- HTTP proxy:
http://proxy.example.com:8080 - HTTPS proxy:
https://proxy.example.com:8080 - Proxy with authentication:
http://username:password@proxy.example.com:8080
NO_PROXY Format#
TheNO_PROXY environment variable supports several formats:
*- Bypass proxy for all hostsexample.com- Exact host name match.example.com- Domain suffix match (matchessub.example.com)*.example.com- Wildcard domain match192.168.1.100- Exact IP address match192.168.1.1-192.168.1.100- IP address rangeexample.com:8080- Hostname with specific port
Multiple entries should be separated by commas.
Example#
To start a Node.js process with proxy support enabled for all requests sentthrough the default global agent, either use theNODE_USE_ENV_PROXY environmentvariable:
NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node client.jsOr the--use-env-proxy flag.
HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node --use-env-proxy client.jsTo create a custom agent with built-in proxy support:
const http =require('node:http');// Creating a custom agent with custom proxy support.const agent =new http.Agent({proxyEnv: {HTTP_PROXY:'http://proxy.example.com:8080' } });http.request({hostname:'www.example.com',port:80,path:'/', agent,},(res) => {// This request will be proxied through proxy.example.com:8080 using the HTTP protocol.console.log(`STATUS:${res.statusCode}`);});Alternatively, the following also works:
const http =require('node:http');// Use lower-cased option name.const agent1 =new http.Agent({proxyEnv: {http_proxy:'http://proxy.example.com:8080' } });// Use values inherited from the environment variables, if the process is started with// HTTP_PROXY=http://proxy.example.com:8080 this will use the proxy server specified// in process.env.HTTP_PROXY.const agent2 =new http.Agent({proxyEnv: process.env });