{ "source": "doc/api/http.md", "modules": [ { "textRaw": "HTTP", "name": "http", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
To use the HTTP server and client one must require('http')
.
The HTTP interfaces in Node.js are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.
\nHTTP message headers are represented by an object like this:
\n\n{ 'content-length': '123',\n 'content-type': 'text/plain',\n 'connection': 'keep-alive',\n 'host': 'mysite.com',\n 'accept': '*/*' }\n
\nKeys are lowercased. Values are not modified.
\nIn order to support the full spectrum of possible HTTP applications, Node.js's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.
\nSee message.headers
for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
\nproperty, which is an array of [key, value, key2, value2, ...]
. For\nexample, the previous message header object might have a rawHeaders
\nlist like the following:
[ 'ConTent-Length', '123456',\n 'content-LENGTH', '123',\n 'content-type', 'text/plain',\n 'CONNECTION', 'keep-alive',\n 'Host', 'mysite.com',\n 'accepT', '*/*' ]\n
\n",
"classes": [
{
"textRaw": "Class: http.Agent",
"type": "class",
"name": "http.Agent",
"meta": {
"added": [
"v0.3.4"
],
"changes": []
},
"desc": "An Agent
is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive
option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent
will still make\nthe requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).
\nIt is good practice, to destroy()
an Agent
instance when it is no\nlonger in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either\na 'close'
event or an 'agentRemove'
event. When intending to keep one\nHTTP request open for a long time without keeping it in the agent, something\nlike the following may be done:
http.get(options, (res) => {\n // Do stuff\n}).on('socket', (socket) => {\n socket.emit('agentRemove');\n});\n
\nAn agent may also be used for an individual request. By providing\n{agent: false}
as an option to the http.get()
or http.request()
\nfunctions, a one-time use Agent
with default options will be used\nfor the client connection.
agent:false
:
http.get({\n hostname: 'localhost',\n port: 80,\n path: '/',\n agent: false // create a new agent just for this one request\n}, (res) => {\n // Do stuff with response\n});\n
\n",
"methods": [
{
"textRaw": "agent.createConnection(options[, callback])",
"type": "method",
"name": "createConnection",
"meta": {
"added": [
"v0.11.4"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {net.Socket} ",
"name": "return",
"type": "net.Socket"
},
"params": [
{
"textRaw": "`options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options ",
"name": "options",
"type": "Object",
"desc": "Options containing connection details. Check [`net.createConnection()`][] for the format of the options"
},
{
"textRaw": "`callback` {Function} Callback function that receives the created socket ",
"name": "callback",
"type": "Function",
"desc": "Callback function that receives the created socket",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Produces a socket/stream to be used for HTTP requests.
\nBy default, this function is the same as net.createConnection()
. However,\ncustom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the\nsocket/stream from this function, or by passing the socket/stream to callback
.
callback
has a signature of (err, stream)
.
Called when socket
is detached from a request and could be persisted by the\nAgent. Default behavior is to:
socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n
\nThis method can be overridden by a particular Agent
subclass. If this\nmethod returns a falsy value, the socket will be destroyed instead of persisting\nit for use with the next request.
Called when socket
is attached to request
after being persisted because of\nthe keep-alive options. Default behavior is to:
socket.ref();\n
\nThis method can be overridden by a particular Agent
subclass.
Destroy any sockets that are currently in use by the agent.
\nIt is usually not necessary to do this. However, if using an\nagent with keepAlive
enabled, then it is best to explicitly shut down\nthe agent when it will no longer be used. Otherwise,\nsockets may hang open for quite a long time before the server\nterminates them.
Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress
or host:port:localAddress:family
. For an HTTPS agent,\nthe name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options\nthat determine socket reusability.
An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive
is enabled. Do not modify.
By default set to 256. For agents with keepAlive
enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is the returned value of agent.getName()
.
An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.
\n" }, { "textRaw": "`sockets` {Object} ", "type": "Object", "name": "sockets", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "desc": "An object which contains arrays of sockets currently in use by the\nagent. Do not modify.
\n" } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the following fields: ", "options": [ { "textRaw": "`keepAlive` {boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Defaults to `false` ", "name": "keepAlive", "type": "boolean", "desc": "Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Defaults to `false`" }, { "textRaw": "`keepAliveMsecs` {number} When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Defaults to `1000`. ", "name": "keepAliveMsecs", "type": "number", "desc": "When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Defaults to `1000`." }, { "textRaw": "`maxSockets` {number} Maximum number of sockets to allow per host. Defaults to `Infinity`. ", "name": "maxSockets", "type": "number", "desc": "Maximum number of sockets to allow per host. Defaults to `Infinity`." }, { "textRaw": "`maxFreeSockets` {number} Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Defaults to `256`. ", "name": "maxFreeSockets", "type": "number", "desc": "Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Defaults to `256`." } ], "name": "options", "type": "Object", "desc": "Set of configurable options to set on the agent. Can have the following fields:", "optional": true } ], "desc": "The default http.globalAgent
that is used by http.request()
has all\nof these values set to their respective defaults.
To configure any of them, a custom http.Agent
instance must be created.
const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n"
},
{
"params": [
{
"name": "options",
"optional": true
}
],
"desc": "The default http.globalAgent
that is used by http.request()
has all\nof these values set to their respective defaults.
To configure any of them, a custom http.Agent
instance must be created.
const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n"
}
]
},
{
"textRaw": "Class: http.ClientRequest",
"type": "class",
"name": "http.ClientRequest",
"meta": {
"added": [
"v0.1.17"
],
"changes": []
},
"desc": "This object is created internally and returned from http.request()
. It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value)
,\n getHeader(name)
, removeHeader(name)
API. The actual header will\nbe sent along with the first data chunk or when calling request.end()
.
To get the response, add a listener for 'response'
to the request object.\n'response'
will be emitted from the request object when the response\nheaders have been received. The 'response'
event is executed with one\nargument which is an instance of http.IncomingMessage
.
During the 'response'
event, one can add listeners to the\nresponse object; particularly to listen for the 'data'
event.
If no 'response'
handler is added, then the response will be\nentirely discarded. However, if a 'response'
event handler is added,\nthen the data from the response object must be consumed, either by\ncalling response.read()
whenever there is a 'readable'
event, or\nby adding a 'data'
handler, or by calling the .resume()
method.\nUntil the data is consumed, the 'end'
event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.
Note: Node.js does not check whether Content-Length and the length of the\nbody which has been transmitted are equal or not.
\nThe request implements the Writable Stream interface. This is an\nEventEmitter
with the following events:
Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort()
.
Emitted each time a server responds to a request with a CONNECT
method. If this\nevent is not being listened for, clients receiving a CONNECT
method will have\ntheir connections closed.
A client and server pair demonstrating how to listen for the 'connect'
event:
const http = require('http');\nconst net = require('net');\nconst url = require('url');\n\n// Create an HTTP tunneling proxy\nconst proxy = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nproxy.on('connect', (req, cltSocket, head) => {\n // connect to an origin server\n const srvUrl = url.parse(`http://${req.url}`);\n const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {\n cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n 'Proxy-agent: Node.js-Proxy\\r\\n' +\n '\\r\\n');\n srvSocket.write(head);\n srvSocket.pipe(cltSocket);\n cltSocket.pipe(srvSocket);\n });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n // make a request to a tunneling proxy\n const options = {\n port: 1337,\n hostname: '127.0.0.1',\n method: 'CONNECT',\n path: 'www.google.com:80'\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('connect', (res, socket, head) => {\n console.log('got connected!');\n\n // make a request over an HTTP tunnel\n socket.write('GET / HTTP/1.1\\r\\n' +\n 'Host: www.google.com:80\\r\\n' +\n 'Connection: close\\r\\n' +\n '\\r\\n');\n socket.on('data', (chunk) => {\n console.log(chunk.toString());\n });\n socket.on('end', () => {\n proxy.close();\n });\n });\n});\n
\n"
},
{
"textRaw": "Event: 'continue'",
"type": "event",
"name": "continue",
"meta": {
"added": [
"v0.3.2"
],
"changes": []
},
"desc": "Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.
\n", "params": [] }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "meta": { "added": [ "v0.1.0" ], "changes": [] }, "params": [], "desc": "Emitted when a response is received to this request. This event is emitted only\nonce.
\n" }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "params": [], "desc": "Emitted after a socket is assigned to this request.
\n" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v0.7.8" ], "changes": [] }, "desc": "Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be aborted manually.
\nSee also: request.setTimeout()
Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for, clients receiving an upgrade header will have\ntheir connections closed.
\nA client server pair demonstrating how to listen for the 'upgrade'
event.
const http = require('http');\n\n// Create an HTTP server\nconst srv = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nsrv.on('upgrade', (req, socket, head) => {\n socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n '\\r\\n');\n\n socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', () => {\n\n // make a request\n const options = {\n port: 1337,\n hostname: '127.0.0.1',\n headers: {\n 'Connection': 'Upgrade',\n 'Upgrade': 'websocket'\n }\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('upgrade', (res, socket, upgradeHead) => {\n console.log('got upgraded!');\n socket.end();\n process.exit(0);\n });\n});\n
\n"
}
],
"methods": [
{
"textRaw": "request.abort()",
"type": "method",
"name": "abort",
"meta": {
"added": [
"v0.3.8"
],
"changes": []
},
"desc": "Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.end([data[, encoding]][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer", "optional": true }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'
.
If data
is specified, it is equivalent to calling\nrequest.write(data, encoding)
followed by request.end(callback)
.
If callback
is specified, it will be called when the request stream\nis finished.
Flush the request headers.
\nFor efficiency reasons, Node.js normally buffers the request headers until\nrequest.end()
is called or the first chunk of request data is written. It\nthen tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. request.flushHeaders()
bypasses\nthe optimization and kickstarts the request.
Reads out a header on the request. Note that the name is case insensitive.
\nExample:
\nconst contentType = request.getHeader('Content-Type');\n
\n"
},
{
"textRaw": "request.removeHeader(name)",
"type": "method",
"name": "removeHeader",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Removes a header that's already defined into headers object.
\nExample:
\nrequest.removeHeader('Content-Type');\n
\n"
},
{
"textRaw": "request.setHeader(name, value)",
"type": "method",
"name": "setHeader",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string} ",
"name": "value",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
},
{
"name": "value"
}
]
}
],
"desc": "Sets a single header value for headers object. If this header already exists in\nthe to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.
\nExample:
\nrequest.setHeader('Content-Type', 'application/json');\n
\nor
\nrequest.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n"
},
{
"textRaw": "request.setNoDelay([noDelay])",
"type": "method",
"name": "setNoDelay",
"meta": {
"added": [
"v0.5.9"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`noDelay` {boolean} ",
"name": "noDelay",
"type": "boolean",
"optional": true
}
]
},
{
"params": [
{
"name": "noDelay",
"optional": true
}
]
}
],
"desc": "Once a socket is assigned to this request and is connected\nsocket.setNoDelay()
will be called.
Once a socket is assigned to this request and is connected\nsocket.setKeepAlive()
will be called.
Once a socket is assigned to this request and is connected\nsocket.setTimeout()
will be called.
Returns request
.
Sends a chunk of the body. By calling this method\nmany times, a request body can be sent to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked']
header line when\ncreating the request.
The encoding
argument is optional and only applies when chunk
is a string.\nDefaults to 'utf8'
.
The callback
argument is optional and will be called when this chunk of data\nis flushed.
Returns request
.
If a request has been aborted, this value is the time when the request was\naborted, in milliseconds since 1 January 1970 00:00:00 UTC.
\n" }, { "textRaw": "`connection` {net.Socket} ", "type": "net.Socket", "name": "connection", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "See request.socket
Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable'
events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end()
, the property is nulled. The socket
may also be accessed\nvia request.connection
.
Example:
\nconst http = require('http');\nconst options = {\n host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n const ip = req.socket.localAddress;\n const port = req.socket.localPort;\n console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n // consume response object\n});\n
\n"
}
]
},
{
"textRaw": "Class: http.Server",
"type": "class",
"name": "http.Server",
"meta": {
"added": [
"v0.1.17"
],
"changes": []
},
"desc": "This class inherits from net.Server
and has the following additional events:
Emitted each time a request with an HTTP Expect: 100-continue
is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g. 400 Bad Request) if the client should not continue to send the\nrequest body.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
Emitted each time a request with an HTTP Expect
header is received, where the\nvalue is not 100-continue
. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed
as appropriate.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
If a client connection emits an 'error'
event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with an\nHTTP '400 Bad Request' response instead of abruptly severing the connection.
Default behavior is to destroy the socket immediately on malformed request.
\nsocket
is the net.Socket
object that the error originated from.
const http = require('http');\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n
\nWhen the 'clientError'
event occurs, there is no request
or response
\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket
object. Care must be taken to\nensure the response is a properly formatted HTTP response message.
Emitted when the server closes.
\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [], "desc": "Emitted each time a client requests an HTTP CONNECT
method. If this event is\nnot listened for, then clients requesting a CONNECT
method will have their\nconnections closed.
After this event is emitted, the request's socket will not have a 'data'
\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.
When a new TCP stream is established. socket
is an object of type\nnet.Socket
. Usually users will not want to access this event. In\nparticular, the socket will not emit 'readable'
events because of how\nthe protocol parser attaches to the socket. The socket
can also be\naccessed at request.connection
.
Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).
\n" }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "params": [], "desc": "Emitted each time a client requests an HTTP upgrade. If this event is not\nlistened for, then clients requesting an upgrade will have their connections\nclosed.
\nAfter this event is emitted, the request's socket will not have a 'data'
\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.
Stops the server from accepting new connections. See net.Server.close()
.
Starts the HTTP server listening for connections.\nThis method is identical to server.listen()
from net.Server
.
Sets the timeout value for sockets, and emits a 'timeout'
event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.
If there is a 'timeout'
event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.
By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if a callback is assigned\nto the Server's 'timeout'
event, timeouts must be handled explicitly.
Returns server
.
A Boolean indicating whether or not the server is listening for\nconnections.
\n" }, { "textRaw": "`maxHeadersCount` {number} Defaults to 2000. ", "type": "number", "name": "maxHeadersCount", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "Limits maximum incoming headers count, equal to 2000 by default. If set to 0 -\nno limit will be applied.
\n", "shortDesc": "Defaults to 2000." }, { "textRaw": "`timeout` {number} Timeout in milliseconds. Defaults to 120000 (2 minutes). ", "type": "number", "name": "timeout", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "desc": "The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nA value of 0 will disable the timeout behavior on incoming connections.
\nNote: The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
\n", "shortDesc": "Timeout in milliseconds. Defaults to 120000 (2 minutes)." }, { "textRaw": "`keepAliveTimeout` {number} Timeout in milliseconds. Defaults to 5000 (5 seconds). ", "type": "number", "name": "keepAliveTimeout", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "The number of milliseconds of inactivity a server needs to wait for additional\nincoming data, after it has finished writing the last response, before a socket\nwill be destroyed. If the server receives new data before the keep-alive\ntimeout has fired, it will reset the regular inactivity timeout, i.e.,\nserver.timeout
.
A value of 0 will disable the keep-alive timeout behavior on incoming connections.
\nNote: The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
\n", "shortDesc": "Timeout in milliseconds. Defaults to 5000 (5 seconds)." } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "This object is created internally by an HTTP server--not by the user. It is\npassed as the second parameter to the 'request'
event.
The response implements, but does not inherit from, the Writable Stream\ninterface. This is an EventEmitter
with the following events:
Indicates that the underlying connection was terminated before\nresponse.end()
was called or able to flush.
Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.
\nAfter this event, no more events will be emitted on the response object.
\n", "params": [] } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object} ", "name": "headers", "type": "Object" } ] }, { "params": [ { "name": "headers" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nTrailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.
\nNote that HTTP requires the Trailer
header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,
response.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end()
, MUST be called on each response.
If data
is specified, it is equivalent to calling\nresponse.write(data, encoding)
followed by response.end(callback)
.
If callback
is specified, it will be called when the response stream\nis finished.
Reads out a header that's already been queued but not sent to the client.\nNote that the name is case insensitive.
\nExample:
\nconst contentType = response.getHeader('content-type');\n
\n"
},
{
"textRaw": "response.getHeaderNames()",
"type": "method",
"name": "getHeaderNames",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Array} ",
"name": "return",
"type": "Array"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nExample:
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
\n"
},
{
"textRaw": "response.getHeaders()",
"type": "method",
"name": "getHeaders",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"name": "return",
"type": "Object"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nNote: The object returned by the response.getHeaders()
method does not\nprototypically inherit from the JavaScript Object
. This means that typical\nObject
methods such as obj.toString()
, obj.hasOwnProperty()
, and others\nare not defined and will not work.
Example:
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
\n"
},
{
"textRaw": "response.hasHeader(name)",
"type": "method",
"name": "hasHeader",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean} ",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Returns true
if the header identified by name
is currently set in the\noutgoing headers. Note that the header name matching is case-insensitive.
Example:
\nconst hasContentType = response.hasHeader('content-type');\n
\n"
},
{
"textRaw": "response.removeHeader(name)",
"type": "method",
"name": "removeHeader",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Removes a header that's queued for implicit sending.
\nExample:
\nresponse.removeHeader('Content-Encoding');\n
\n"
},
{
"textRaw": "response.setHeader(name, value)",
"type": "method",
"name": "setHeader",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string | string[]} ",
"name": "value",
"type": "string | string[]"
}
]
},
{
"params": [
{
"name": "name"
},
{
"name": "value"
}
]
}
],
"desc": "Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.
\nExample:
\nresponse.setHeader('Content-Type', 'text/html');\n
\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
When headers have been set with response.setHeader()
, they will be merged with\nany headers passed to response.writeHead()
, with the headers passed to\nresponse.writeHead()
given precedence.
// returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n
\n"
},
{
"textRaw": "response.setTimeout(msecs[, callback])",
"type": "method",
"name": "setTimeout",
"meta": {
"added": [
"v0.9.12"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {number} ",
"name": "msecs",
"type": "number"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "msecs"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Sets the Socket's timeout value to msecs
. If a callback is\nprovided, then it is added as a listener on the 'timeout'
event on\nthe response object.
If no 'timeout'
listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If a handler is\nassigned to the request, the response, or the server's 'timeout'
events,\ntimed out sockets must be handled explicitly.
Returns response
.
If this method is called and response.writeHead()
has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nNote that in the http
module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204
and 304
responses\nmust not include a message body.
chunk
can be a string or a buffer. If chunk
is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding
is 'utf8'
. callback
will be called when this chunk\nof data is flushed.
Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.
\nThe first time response.write()
is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write()
is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
Returns true
if the entire data was flushed successfully to the kernel\nbuffer. Returns false
if all or part of the data was queued in user memory.\n'drain'
will be emitted when the buffer is free again.
Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue'
event on Server
.
Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404
. The last argument, headers
, are the response headers.\nOptionally one can give a human-readable statusMessage
as the second\nargument.
Example:
\nconst body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain' });\n
\nThis method must only be called once on a message and it must\nbe called before response.end()
is called.
If response.write()
or response.end()
are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader()
, they will be merged with\nany headers passed to response.writeHead()
, with the headers passed to\nresponse.writeHead()
given precedence.
// returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n
\nNote that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world'
contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()
\nshould be used to determine the number of bytes in a given encoding.\nAnd Node.js does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
See response.socket
.
Boolean value that indicates whether the response has completed. Starts\nas false
. After response.end()
executes, the value will be true
.
Boolean (read-only). True if headers were sent, false otherwise.
\n" }, { "textRaw": "`sendDate` {boolean} ", "type": "boolean", "name": "sendDate", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "desc": "When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; HTTP requires the Date header\nin responses.
\n" }, { "textRaw": "`socket` {net.Socket} ", "type": "net.Socket", "name": "socket", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable'
events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end()
, the property is nulled. The socket
may also be accessed\nvia response.connection
.
Example:
\nconst http = require('http');\nconst server = http.createServer((req, res) => {\n const ip = res.socket.remoteAddress;\n const port = res.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
\n"
},
{
"textRaw": "`statusCode` {number} ",
"type": "number",
"name": "statusCode",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"desc": "When using implicit headers (not calling response.writeHead()
explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
Example:
\nresponse.statusCode = 404;\n
\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
\n" }, { "textRaw": "`statusMessage` {string} ", "type": "string", "name": "statusMessage", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "When using implicit headers (not calling response.writeHead()
explicitly), this property\ncontrols the status message that will be sent to the client when the headers get\nflushed. If this is left as undefined
then the standard message for the status\ncode will be used.
Example:
\nresponse.statusMessage = 'Not found';\n
\nAfter response header was sent to the client, this property indicates the\nstatus message which was sent out.
\n" } ] }, { "textRaw": "Class: http.IncomingMessage", "type": "class", "name": "http.IncomingMessage", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "An IncomingMessage
object is created by http.Server
or\nhttp.ClientRequest
and passed as the first argument to the 'request'
\nand 'response'
event respectively. It may be used to access response status,\nheaders and data.
It implements the Readable Stream interface, as well as the\nfollowing additional events, methods, and properties.
\n", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v0.3.8" ], "changes": [] }, "desc": "Emitted when the request has been aborted and the network socket has closed.
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.4.2" ], "changes": [] }, "desc": "Indicates that the underlying connection was closed.\nJust like 'end'
, this event occurs only once per response.
Calls destroy()
on the socket that received the IncomingMessage
. If error
\nis provided, an 'error'
event is emitted and error
is passed as an argument\nto any listeners on the event.
Calls message.connection.setTimeout(msecs, callback)
.
Returns message
.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.\nExample:
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n
\nDuplicates in raw headers are handled in the following ways, depending on the\nheader name:
\nage
, authorization
, content-length
, content-type
,\netag
, expires
, from
, host
, if-modified-since
, if-unmodified-since
,\nlast-modified
, location
, max-forwards
, proxy-authorization
, referer
,\nretry-after
, or user-agent
are discarded.set-cookie
is always an array. Duplicates are added to the array.In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1'
or '1.0'
.
Also message.httpVersionMajor
is the first integer and\nmessage.httpVersionMinor
is the second.
Only valid for request obtained from http.Server
.
The request method as a string. Read only. Example:\n'GET'
, 'DELETE'
.
The raw request/response headers list exactly as they were received.
\nNote that the keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.
\nHeader names are not lowercased, and duplicates are not merged.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n
\n"
},
{
"textRaw": "`rawTrailers` {Array} ",
"type": "Array",
"name": "rawTrailers",
"meta": {
"added": [
"v0.11.6"
],
"changes": []
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end'
event.
The net.Socket
object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate()
to obtain the\nclient's authentication details.
Only valid for response obtained from http.ClientRequest
.
The 3-digit HTTP response status code. E.G. 404
.
Only valid for response obtained from http.ClientRequest
.
The HTTP response status message (reason phrase). E.G. OK
or Internal Server Error
.
The request/response trailers object. Only populated at the 'end'
event.
Only valid for request obtained from http.Server
.
Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:
\nGET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n
\nThen request.url
will be:
'/status?name=ryan'\n
\nTo parse the url into its parts require('url').parse(request.url)
\ncan be used. Example:
$ node\n> require('url').parse('/status?name=ryan')\nUrl {\n protocol: null,\n slashes: null,\n auth: null,\n host: null,\n port: null,\n hostname: null,\n hash: null,\n search: '?name=ryan',\n query: 'name=ryan',\n pathname: '/status',\n path: '/status?name=ryan',\n href: '/status?name=ryan' }\n
\nTo extract the parameters from the query string, the\nrequire('querystring').parse
function can be used, or\ntrue
can be passed as the second argument to require('url').parse
.\nExample:
$ node\n> require('url').parse('/status?name=ryan', true)\nUrl {\n protocol: null,\n slashes: null,\n auth: null,\n host: null,\n port: null,\n hostname: null,\n hash: null,\n search: '?name=ryan',\n query: { name: 'ryan' },\n pathname: '/status',\n path: '/status?name=ryan',\n href: '/status?name=ryan' }\n
\n"
}
]
}
],
"properties": [
{
"textRaw": "`METHODS` {Array} ",
"type": "Array",
"name": "METHODS",
"meta": {
"added": [
"v0.11.8"
],
"changes": []
},
"desc": "A list of the HTTP methods that are supported by the parser.
\n" }, { "textRaw": "`STATUS_CODES` {Object} ", "type": "Object", "name": "STATUS_CODES", "meta": { "added": [ "v0.1.22" ], "changes": [] }, "desc": "A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'
.
Global instance of Agent
which is used as the default for all HTTP client\nrequests.
Returns a new instance of http.Server
.
The requestListener
is a function which is automatically\nadded to the 'request'
event.
Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request()
is that it sets the method to GET and calls req.end()
\nautomatically. Note that the callback must take care to consume the response\ndata for reasons stated in http.ClientRequest
section.
The callback
is invoked with a single argument that is an instance of\nhttp.IncomingMessage
JSON Fetching Example:
\nhttp.get('http://nodejs.org/dist/index.json', (res) => {\n const { statusCode } = res;\n const contentType = res.headers['content-type'];\n\n let error;\n if (statusCode !== 200) {\n error = new Error('Request Failed.\\n' +\n `Status Code: ${statusCode}`);\n } else if (!/^application\\/json/.test(contentType)) {\n error = new Error('Invalid content-type.\\n' +\n `Expected application/json but received ${contentType}`);\n }\n if (error) {\n console.error(error.message);\n // consume response data to free up memory\n res.resume();\n return;\n }\n\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => { rawData += chunk; });\n res.on('end', () => {\n try {\n const parsedData = JSON.parse(rawData);\n console.log(parsedData);\n } catch (e) {\n console.error(e.message);\n }\n });\n}).on('error', (e) => {\n console.error(`Got error: ${e.message}`);\n});\n
\n"
},
{
"textRaw": "http.request(options[, callback])",
"type": "method",
"name": "request",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {http.ClientRequest} ",
"name": "return",
"type": "http.ClientRequest"
},
"params": [
{
"textRaw": "`options` {Object | string | URL} ",
"options": [
{
"textRaw": "`protocol` {string} Protocol to use. Defaults to `http:`. ",
"name": "protocol",
"type": "string",
"desc": "Protocol to use. Defaults to `http:`."
},
{
"textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. Defaults to `localhost`. ",
"name": "host",
"type": "string",
"desc": "A domain name or IP address of the server to issue the request to. Defaults to `localhost`."
},
{
"textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`. ",
"name": "hostname",
"type": "string",
"desc": "Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`."
},
{
"textRaw": "`family` {number} IP address family to use when resolving `host` and `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used. ",
"name": "family",
"type": "number",
"desc": "IP address family to use when resolving `host` and `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used."
},
{
"textRaw": "`port` {number} Port of remote server. Defaults to 80. ",
"name": "port",
"type": "number",
"desc": "Port of remote server. Defaults to 80."
},
{
"textRaw": "`localAddress` {string} Local interface to bind for network connections. ",
"name": "localAddress",
"type": "string",
"desc": "Local interface to bind for network connections."
},
{
"textRaw": "`socketPath` {string} Unix Domain Socket (use one of host:port or socketPath). ",
"name": "socketPath",
"type": "string",
"desc": "Unix Domain Socket (use one of host:port or socketPath)."
},
{
"textRaw": "`method` {string} A string specifying the HTTP request method. Defaults to `'GET'`. ",
"name": "method",
"type": "string",
"desc": "A string specifying the HTTP request method. Defaults to `'GET'`."
},
{
"textRaw": "`path` {string} Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. ",
"name": "path",
"type": "string",
"desc": "Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future."
},
{
"textRaw": "`headers` {Object} An object containing request headers. ",
"name": "headers",
"type": "Object",
"desc": "An object containing request headers."
},
{
"textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header. ",
"name": "auth",
"type": "string",
"desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header."
},
{
"textRaw": "`agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values: ",
"options": [
{
"textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port. ",
"name": "undefined",
"default": "",
"desc": ": use [`http.globalAgent`][] for this host and port."
},
{
"textRaw": "`Agent` object: explicitly use the passed in `Agent`. ",
"name": "Agent",
"desc": "object: explicitly use the passed in `Agent`."
},
{
"textRaw": "`false`: causes a new `Agent` with default values to be used. ",
"name": "false",
"desc": "causes a new `Agent` with default values to be used."
}
],
"name": "agent",
"type": "http.Agent | boolean",
"desc": "Controls [`Agent`][] behavior. Possible values:"
},
{
"textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. ",
"name": "createConnection",
"type": "Function",
"desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details."
},
{
"textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected. ",
"name": "timeout",
"type": "number",
"desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected."
}
],
"name": "options",
"type": "Object | string | URL"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.
\noptions
can be an object, a string, or a URL
object. If options
is a\nstring, it is automatically parsed with url.parse()
. If it is a URL
\nobject, it will be automatically converted to an ordinary options
object.
The optional callback
parameter will be added as a one time listener for\nthe 'response'
event.
http.request()
returns an instance of the http.ClientRequest
\nclass. The ClientRequest
instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest
object.
Example:
\nconst postData = querystring.stringify({\n 'msg': 'Hello World!'\n});\n\nconst options = {\n hostname: 'www.google.com',\n port: 80,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': Buffer.byteLength(postData)\n }\n};\n\nconst req = http.request(options, (res) => {\n console.log(`STATUS: ${res.statusCode}`);\n console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n res.setEncoding('utf8');\n res.on('data', (chunk) => {\n console.log(`BODY: ${chunk}`);\n });\n res.on('end', () => {\n console.log('No more data in response.');\n });\n});\n\nreq.on('error', (e) => {\n console.error(`problem with request: ${e.message}`);\n});\n\n// write data to request body\nreq.write(postData);\nreq.end();\n
\nNote that in the example req.end()
was called. With http.request()
one\nmust always call req.end()
to signify the end of the request -\neven if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error'
event is emitted\non the returned request object. As with all 'error'
events, if no listeners\nare registered the error will be thrown.
There are a few special headers that should be noted.
\nSending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.
\nSending a 'Content-Length' header will disable the default chunked encoding.
\nSending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the continue
event should be set. See RFC2616 Section 8.2.3 for more\ninformation.
Sending an Authorization header will override using the auth
option\nto compute basic authentication.
Example using a URL
as options
:
const { URL } = require('url');\n\nconst options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n // ...\n});\n
\n"
}
],
"type": "module",
"displayName": "HTTP"
}
]
}