{ "source": "doc/api/http.md", "modules": [ { "textRaw": "HTTP", "name": "http", "stability": 2, "stabilityText": "Stable", "desc": "

To use the HTTP server and client one must require('http').

\n

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.

\n

HTTP message headers are represented by an object like this:

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'host': 'mysite.com',\n  'accept': '*/*' }\n

Keys are lowercased. Values are not modified.

\n

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

\n

See [message.headers][] for details on how duplicate headers are handled.

\n

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:

\n
[ 'ConTent-Length', '123456',\n  'content-LENGTH', '123',\n  'content-type', 'text/plain',\n  'CONNECTION', 'keep-alive',\n  'Host', 'mysite.com',\n  'accepT', '*/*' ]\n
", "classes": [ { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "meta": { "added": [ "v0.3.4" ] }, "desc": "

The HTTP Agent is used for pooling sockets used in HTTP client\nrequests.

\n

The HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a\nsocket to become free the socket is closed. This means that Node.js's\npool has the benefit of keep-alive when under load but still does not\nrequire developers to manually close the HTTP clients using\nKeepAlive.

\n

If you opt into using HTTP KeepAlive, you can create an Agent object\nwith that flag set to true. (See the [constructor options][].)\nThen, the Agent will keep unused sockets in a pool for later use. They\nwill be explicitly marked so as to not keep the Node.js process running.\nHowever, it is still a good idea to explicitly [destroy()][] KeepAlive\nagents when they are no longer in use, so that the Sockets will be shut\ndown.

\n

Sockets are removed from the agent's pool when the socket emits either\na 'close' event or a special 'agentRemove' event. This means that if\nyou intend to keep one HTTP request open for a long time and don't\nwant it to stay in the pool you can do something along the lines of:

\n
http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});\n
\n

Alternatively, you could just opt out of pooling entirely using\nagent:false:

\n
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" ] }, "desc": "

Produces a socket/stream to be used for HTTP requests.

\n

By default, this function is the same as [net.createConnection()][]. However,\ncustom Agents may override this method in case greater flexibility is desired.

\n

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.

\n

callback has a signature of (err, stream).

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "agent.destroy()", "type": "method", "name": "destroy", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Destroy any sockets that are currently in use by the agent.

\n

It is usually not necessary to do this. However, if you are using an\nagent with KeepAlive enabled, then it is best to explicitly shut down\nthe agent when you know that it will no longer be used. Otherwise,\nsockets may hang open for quite a long time before the server\nterminates them.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "agent.getName(options)", "type": "method", "name": "getName", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Get a unique name for a set of request options, to determine whether a\nconnection can be reused. In the http agent, this returns\nhost:port:localAddress. In the https agent, the name includes the\nCA, cert, ciphers, and other HTTPS/TLS-specific options that determine\nsocket reusability.

\n

Options:

\n\n", "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "properties": [ { "textRaw": "agent.freeSockets", "name": "freeSockets", "meta": { "added": [ "v0.11.4" ] }, "desc": "

An object which contains arrays of sockets currently awaiting use by\nthe Agent when HTTP KeepAlive is used. Do not modify.

\n" }, { "textRaw": "agent.maxFreeSockets", "name": "maxFreeSockets", "meta": { "added": [ "v0.11.7" ] }, "desc": "

By default set to 256. For Agents supporting HTTP KeepAlive, this\nsets the maximum number of sockets that will be left open in the free\nstate.

\n" }, { "textRaw": "agent.maxSockets", "name": "maxSockets", "meta": { "added": [ "v0.3.6" ] }, "desc": "

By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is either a 'host:port' or\n'host:port:localAddress' combination.

\n" }, { "textRaw": "agent.requests", "name": "requests", "meta": { "added": [ "v0.5.9" ] }, "desc": "

An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.

\n" }, { "textRaw": "agent.sockets", "name": "sockets", "meta": { "added": [ "v0.3.6" ] }, "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 in a pool to be used by other requests in the future. Default = `false` ", "name": "keepAlive", "type": "Boolean", "desc": "Keep sockets around in a pool to be used by other requests in the future. Default = `false`" }, { "textRaw": "`keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = `1000`. Only relevant if `keepAlive` is set to `true`. ", "name": "keepAliveMsecs", "type": "Integer", "desc": "When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = `1000`. Only relevant if `keepAlive` is set to `true`." }, { "textRaw": "`maxSockets` {Number} Maximum number of sockets to allow per host. Default = `Infinity`. ", "name": "maxSockets", "type": "Number", "desc": "Maximum number of sockets to allow per host. Default = `Infinity`." }, { "textRaw": "`maxFreeSockets` {Number} Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `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`. Default = `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.

\n

To configure any of them, you must create your own [http.Agent][] object.

\n
const http = require('http');\nvar 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.

\n

To configure any of them, you must create your own [http.Agent][] object.

\n
const http = require('http');\nvar 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" ] }, "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), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.

\n

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][].

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.

\n

If no 'response' handler is added, then the response will be\nentirely discarded. However, if you add a 'response' event handler,\nthen you must consume the data from the response object, 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.

\n

Note: Node.js does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:

\n", "events": [ { "textRaw": "Event: 'abort'", "type": "event", "name": "abort", "meta": { "added": [ "v1.4.1" ] }, "desc": "

function () { }

\n

Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().

\n", "params": [] }, { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v0.3.8" ] }, "desc": "

function () { }

\n

Emitted when the request has been aborted by the server and the network\nsocket has closed.

\n", "params": [] }, { "textRaw": "Event: 'checkExpectation'", "type": "event", "name": "checkExpectation", "meta": { "added": [ "v5.5.0" ] }, "desc": "

function (request, response) { }

\n

Emitted each time a request with an http Expect header is received, where the\nvalue is not 100-continue. If this event isn't listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "desc": "

function (response, socket, head) { }

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.

\n

A client server pair that show you how to listen for the 'connect' event.

\n
const http = require('http');\nconst net = require('net');\nconst url = require('url');\n\n// Create an HTTP tunneling proxy\nvar 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  var srvUrl = url.parse(`http://${req.url}`);\n  var 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  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var 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", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "meta": { "added": [ "v0.3.2" ] }, "desc": "

function () { }

\n

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" ] }, "desc": "

function (response) { }

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of [http.IncomingMessage][].

\n", "params": [] }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "meta": { "added": [ "v0.5.3" ] }, "desc": "

function (socket) { }

\n

Emitted after a socket is assigned to this request.

\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "desc": "

function (response, socket, head) { }

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.

\n

A client server pair that show you how to listen for the 'upgrade' event.

\n
const http = require('http');\n\n// Create an HTTP server\nvar 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  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var 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", "params": [] } ], "methods": [ { "textRaw": "request.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.3.8" ] }, "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" ] }, "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'.

\n

If data is specified, it is equivalent to calling\n[response.write(data, encoding)][] followed by request.end(callback).

\n

If callback is specified, it will be called when the request stream\nis finished.

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.flushHeaders()", "type": "method", "name": "flushHeaders", "meta": { "added": [ "v1.6.0" ] }, "desc": "

Flush the request headers.

\n

For efficiency reasons, Node.js normally buffers the request headers until you\ncall request.end() or write the first chunk of request data. It then tries\nhard to pack the request headers and data into a single TCP packet.

\n

That's usually what you want (it saves a TCP round-trip) but not when the first\ndata isn't sent until possibly much later. request.flushHeaders() lets you bypass\nthe optimization and kickstart the request.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable][, initialDelay])", "type": "method", "name": "setSocketKeepAlive", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "request.setTimeout(timeout[, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.

\n\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ] }, "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.

\n

The chunk argument should be a [Buffer][] or a string.

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.

\n

The callback argument is optional and will be called when this chunk of data\nis flushed.

\n

Returns request.

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] } ] }, { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "meta": { "added": [ "v0.1.17" ] }, "desc": "

This class inherits from [net.Server][] and has the following additional events:

\n", "events": [ { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "meta": { "added": [ "v0.3.0" ] }, "desc": "

function (request, response) { }

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.

\n

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.

\n

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.

\n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "meta": { "added": [ "v0.1.94" ] }, "desc": "

function (exception, socket) { }

\n

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.

\n

Default behavior is to destroy the socket immediately on malformed request.

\n

socket is the [net.Socket][] object that the error originated from.

\n
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
\n

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

\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.4" ] }, "desc": "

function () { }

\n

Emitted when the server closes.

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "desc": "

function (request, socket, head) { }

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.

\n\n

After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.0" ] }, "desc": "

function (socket) { }

\n

When a new TCP stream is established. socket is an object of type\n[net.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.

\n", "params": [] }, { "textRaw": "Event: 'request'", "type": "event", "name": "request", "meta": { "added": [ "v0.1.0" ] }, "desc": "

function (request, response) { }

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of [http.IncomingMessage][] and response is\nan instance of [http.ServerResponse][].

\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "desc": "

function (request, socket, head) { }

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.

\n\n

After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.

\n", "params": [] } ], "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle[, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.5.10" ] }, "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.

\n

Listening on a file descriptor is not supported on Windows.

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen()][].

\n

Returns server.

\n" }, { "textRaw": "server.listen(path[, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Start a UNIX socket server listening for connections on the given path.

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen(path)][].

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(port[, hostname][, backlog][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections on any IPv6 address\n(::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. Use a\nport value of 0 to have the operating system assign an available port.

\n

To listen to a unix socket, supply a filename instead of port and hostname.

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen(port)][].

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

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.

\n

If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.

\n

By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.

\n

Returns server.

\n" } ], "properties": [ { "textRaw": "server.listening", "name": "listening", "meta": { "added": [ "v5.7.0" ] }, "desc": "

A Boolean indicating whether or not the server is listening for\nconnections.

\n" }, { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "meta": { "added": [ "v0.7.0" ] }, "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.

\n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "type": "Number", "name": "timeout", "meta": { "added": [ "v0.9.12" ] }, "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.

\n

Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.

\n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "meta": { "added": [ "v0.1.17" ] }, "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.

\n

The response implements, but does not inherit from, the [Writable Stream][]\ninterface. This is an [EventEmitter][] with the following events:

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.6.7" ] }, "desc": "

function () { }

\n

Indicates that the underlying connection was terminated before\n[response.end()][] was called or able to flush.

\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v0.3.6" ] }, "desc": "

function () { }

\n

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.

\n

After 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" ] }, "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

\n

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

\n

Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});\nresponse.end();\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.

\n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "desc": "

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.

\n

If data is specified, it is equivalent to calling\n[response.write(data, encoding)][] followed by response.end(callback).

\n

If callback is specified, it will be called when the response stream\nis finished.

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "meta": { "added": [ "v0.4.0" ] }, "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.

\n

Example:

\n
var contentType = response.getHeader('content-type');\n
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "meta": { "added": [ "v0.4.0" ] }, "desc": "

Removes a header that's queued for implicit sending.

\n

Example:

\n
response.removeHeader('Content-Encoding');\n
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "meta": { "added": [ "v0.4.0" ] }, "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 if you need to send multiple headers with the same name.

\n

Example:

\n
response.setHeader('Content-Type', 'text/html');\n
\n

or

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.

\n

When headers have been set with [response.setHeader()][], they will be merged with\nany headers passed to [response.writeHead()][], with the headers passed to\n[response.writeHead()][] given precedence.

\n
// 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", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "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.

\n

If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.

\n

Returns response.

\n" }, { "textRaw": "response.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ] }, "desc": "

If this method is called and [response.writeHead()][] has not been called,\nit will switch to implicit header mode and flush the implicit headers.

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

\n

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'. The last parameter callback\nwill be called when this chunk of data is flushed.

\n

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.

\n

The first time [response.write()][] is called, it will send the buffered\nheader information and the first body to the client. The second time\n[response.write()][] is called, Node.js assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.

\n

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.

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "meta": { "added": [ "v0.3.0" ] }, "desc": "

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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode[, statusMessage][, headers])", "type": "method", "name": "writeHead", "meta": { "added": [ "v0.1.30" ] }, "desc": "

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.

\n

Example:

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain' });\n
\n

This method must only be called once on a message and it must\nbe called before [response.end()][] is called.

\n

If you call [response.write()][] or [response.end()][] before calling this,\nthe implicit/mutable headers will be calculated and call this function for you.

\n

When headers have been set with [response.setHeader()][], they will be merged with\nany headers passed to [response.writeHead()][], with the headers passed to\n[response.writeHead()][] given precedence.

\n
// 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

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

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.

\n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "statusMessage", "optional": true }, { "name": "headers", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.finished", "name": "finished", "meta": { "added": [ "v0.0.2" ] }, "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After [response.end()][] executes, the value will be true.

\n" }, { "textRaw": "response.headersSent", "name": "headersSent", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Boolean (read-only). True if headers were sent, false otherwise.

\n" }, { "textRaw": "response.sendDate", "name": "sendDate", "meta": { "added": [ "v0.7.5" ] }, "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.

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.

\n" }, { "textRaw": "response.statusCode", "name": "statusCode", "meta": { "added": [ "v0.4.0" ] }, "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.

\n

Example:

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

\n" }, { "textRaw": "response.statusMessage", "name": "statusMessage", "meta": { "added": [ "v0.11.8" ] }, "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.

\n

Example:

\n
response.statusMessage = 'Not found';\n
\n

After 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" ] }, "desc": "

An IncomingMessage object is created by [http.Server][] or\n[http.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.

\n

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" ] }, "desc": "

function () { }

\n

Emitted when the request has been aborted by the client and the network\nsocket has closed.

\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.4.2" ] }, "desc": "

function () { }

\n

Indicates that the underlying connection was closed.\nJust like 'end', this event occurs only once per response.

\n", "params": [] } ], "methods": [ { "textRaw": "message.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error", "optional": true } ] }, { "params": [ { "name": "error", "optional": true } ] } ], "desc": "

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.

\n" }, { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Calls message.connection.setTimeout(msecs, callback).

\n

Returns message.

\n" } ], "properties": [ { "textRaw": "message.headers", "name": "headers", "meta": { "added": [ "v0.1.5" ] }, "desc": "

The request/response headers object.

\n

Key-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
\n

Duplicates in raw headers are handled in the following ways, depending on the\nheader name:

\n\n" }, { "textRaw": "message.httpVersion", "name": "httpVersion", "meta": { "added": [ "v0.1.1" ] }, "desc": "

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

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

\n" }, { "textRaw": "message.method", "name": "method", "meta": { "added": [ "v0.1.1" ] }, "desc": "

Only valid for request obtained from [http.Server][].

\n

The request method as a string. Read only. Example:\n'GET', 'DELETE'.

\n" }, { "textRaw": "message.rawHeaders", "name": "rawHeaders", "meta": { "added": [ "v0.11.6" ] }, "desc": "

The raw request/response headers list exactly as they were received.

\n

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

\n

Header 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": "message.rawTrailers", "name": "rawTrailers", "meta": { "added": [ "v0.11.6" ] }, "desc": "

The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

\n" }, { "textRaw": "message.statusCode", "name": "statusCode", "meta": { "added": [ "v0.1.1" ] }, "desc": "

Only valid for response obtained from [http.ClientRequest][].

\n

The 3-digit HTTP response status code. E.G. 404.

\n" }, { "textRaw": "message.statusMessage", "name": "statusMessage", "meta": { "added": [ "v0.11.10" ] }, "desc": "

Only valid for response obtained from [http.ClientRequest][].

\n

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

\n" }, { "textRaw": "message.socket", "name": "socket", "meta": { "added": [ "v0.3.0" ] }, "desc": "

The [net.Socket][] object associated with the connection.

\n

With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the\nclient's authentication details.

\n" }, { "textRaw": "message.trailers", "name": "trailers", "meta": { "added": [ "v0.3.0" ] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

\n" }, { "textRaw": "message.url", "name": "url", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Only valid for request obtained from [http.Server][].

\n

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n

Then request.url will be:

\n
'/status?name=ryan'\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:

\n
$ node\n> require('url').parse('/status?name=ryan')\n{\n  href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status'\n}\n

If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:

\n
$ node\n> require('url').parse('/status?name=ryan', true)\n{\n  href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: {name: 'ryan'},\n  pathname: '/status'\n}\n
" } ] } ], "properties": [ { "textRaw": "`METHODS` {Array} ", "type": "Array", "name": "METHODS", "meta": { "added": [ "v0.11.8" ] }, "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" ] }, "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'.

\n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.

\n" } ], "methods": [ { "textRaw": "http.createClient([port][, host])", "type": "method", "name": "createClient", "meta": { "added": [ "v0.1.13" ], "deprecated": [ "v0.3.6" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`http.request()`][] instead.", "desc": "

Constructs a new HTTP client. port and host refer to the server to be\nconnected to.

\n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.1.13" ] }, "desc": "

Returns a new instance of [http.Server][].

\n

The requestListener is a function which is automatically\nadded to the 'request' event.

\n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.get(options[, callback])", "type": "method", "name": "get", "meta": { "added": [ "v0.3.6" ] }, "desc": "

Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and [http.request()][]\nis that it sets the method to GET and calls req.end() automatically.

\n

Example:

\n
http.get('http://www.google.com/index.html', (res) => {\n  console.log(`Got response: ${res.statusCode}`);\n  // consume response body\n  res.resume();\n}).on('error', (e) => {\n  console.log(`Got error: ${e.message}`);\n});\n
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "http.request(options[, callback])", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ] }, "desc": "

Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].

\n

Options:

\n\n

The optional callback parameter will be added as a one time listener for\nthe 'response' event.

\n

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.

\n

Example:

\n
var postData = querystring.stringify({\n  'msg' : 'Hello World!'\n});\n\nvar 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\nvar 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.log(`problem with request: ${e.message}`);\n});\n\n// write data to request body\nreq.write(postData);\nreq.end();\n
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.

\n

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.

\n

There are a few special headers that should be noted.

\n\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] } ], "type": "module", "displayName": "HTTP" } ] }