- About these Docs
- Synopsis
- Assertion Testing
- Buffer
- C/C++ Addons
- Child Processes
- Cluster
- Command Line Options
- Console
- Crypto
- Debugger
- DNS
- Domain
- Errors
- Events
- File System
- Globals
- HTTP
- HTTPS
- Modules
- Net
- OS
- Path
- Process
- Punycode
- Query Strings
- Readline
- REPL
- Stream
- String Decoder
- Timers
- TLS/SSL
- TTY
- UDP/Datagram
- URL
- Utilities
- V8
- VM
- ZLIB
Node.js v5.12.0 Documentation
Table of Contents
- HTTP
- Class: http.Agent
- Class: http.ClientRequest
- Event: 'abort'
- Event: 'checkExpectation'
- Event: 'connect'
- Event: 'continue'
- Event: 'response'
- Event: 'socket'
- Event: 'upgrade'
- request.abort()
- request.end([data][, encoding][, callback])
- request.flushHeaders()
- request.setNoDelay([noDelay])
- request.setSocketKeepAlive([enable][, initialDelay])
- request.setTimeout(timeout[, callback])
- request.write(chunk[, encoding][, callback])
- Class: http.Server
- Event: 'checkContinue'
- Event: 'clientError'
- Event: 'close'
- Event: 'connect'
- Event: 'connection'
- Event: 'request'
- Event: 'upgrade'
- server.close([callback])
- server.listen(handle[, callback])
- server.listen(path[, callback])
- server.listen(port[, hostname][, backlog][, callback])
- server.listening
- server.maxHeadersCount
- server.setTimeout(msecs, callback)
- server.timeout
- Class: http.ServerResponse
- Event: 'close'
- Event: 'finish'
- response.addTrailers(headers)
- response.end([data][, encoding][, callback])
- response.finished
- response.getHeader(name)
- response.headersSent
- response.removeHeader(name)
- response.sendDate
- response.setHeader(name, value)
- response.setTimeout(msecs, callback)
- response.statusCode
- response.statusMessage
- response.write(chunk[, encoding][, callback])
- response.writeContinue()
- response.writeHead(statusCode[, statusMessage][, headers])
- Class: http.IncomingMessage
- http.METHODS
- http.STATUS_CODES
- http.createClient([port][, host])
- http.createServer([requestListener])
- http.get(options[, callback])
- http.globalAgent
- http.request(options[, callback])
HTTP#
Stability: 2 - Stable
To use the HTTP server and client one must require('http').
The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data.
HTTP message headers are represented by an object like this:
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'host': 'mysite.com',
'accept': '*/*' }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, Node.js's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
See message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders
list like the following:
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'mysite.com',
'accepT', '*/*' ]
Class: http.Agent#
The HTTP Agent is used for pooling sockets used in HTTP client requests.
The HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that Node.js's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using KeepAlive.
If you opt into using HTTP KeepAlive, you can create an Agent object
with that flag set to true. (See the constructor options.)
Then, the Agent will keep unused sockets in a pool for later use. They
will be explicitly marked so as to not keep the Node.js process running.
However, it is still a good idea to explicitly destroy() KeepAlive
agents when they are no longer in use, so that the Sockets will be shut
down.
Sockets are removed from the agent's pool when the socket emits either
a 'close' event or a special 'agentRemove' event. This means that if
you intend to keep one HTTP request open for a long time and don't
want it to stay in the pool you can do something along the lines of:
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
Alternatively, you could just opt out of pooling entirely using
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false // create a new agent just for this one request
}, (res) => {
// Do stuff with response
})
new Agent([options])#
options<Object> Set of configurable options to set on the agent. Can have the following fields:keepAlive<Boolean> Keep sockets around in a pool to be used by other requests in the future. Default =falsekeepAliveMsecs<Integer> When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default =1000. Only relevant ifkeepAliveis set totrue.maxSockets<Number> Maximum number of sockets to allow per host. Default =Infinity.maxFreeSockets<Number> Maximum number of sockets to leave open in a free state. Only relevant ifkeepAliveis set totrue. Default =256.
The default http.globalAgent that is used by http.request() has all
of these values set to their respective defaults.
To configure any of them, you must create your own http.Agent object.
const http = require('http');
var keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
agent.createConnection(options[, callback])#
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as net.createConnection(). However,
custom 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
socket/stream from this function, or by passing the socket/stream to callback.
callback has a signature of (err, stream).
agent.destroy()#
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, sockets may hang open for quite a long time before the server terminates them.
agent.freeSockets#
An object which contains arrays of sockets currently awaiting use by the Agent when HTTP KeepAlive is used. Do not modify.
agent.getName(options)#
Get a unique name for a set of request options, to determine whether a
connection can be reused. In the http agent, this returns
host:port:localAddress. In the https agent, the name includes the
CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
socket reusability.
Options:
host: A domain name or IP address of the server to issue the request to.port: Port of remote server.localAddress: Local interface to bind for network connections when issuing the request.
agent.maxFreeSockets#
By default set to 256. For Agents supporting HTTP KeepAlive, this sets the maximum number of sockets that will be left open in the free state.
agent.maxSockets#
By default set to Infinity. Determines how many concurrent sockets the agent can have open per origin. Origin is either a 'host:port' or 'host:port:localAddress' combination.
agent.requests#
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
agent.sockets#
An object which contains arrays of sockets currently in use by the Agent. Do not modify.
Class: http.ClientRequest#
This object is created internally and returned from http.request(). It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value), getHeader(name),
removeHeader(name) API. The actual header will be sent along with the first
data chunk or when closing the connection.
To get the response, add a listener for 'response' to the request object.
'response' will be emitted from the request object when the response
headers have been received. The 'response' event is executed with one
argument which is an instance of http.IncomingMessage.
During the 'response' event, one can add listeners to the
response object; particularly to listen for the 'data' event.
If no 'response' handler is added, then the response will be
entirely discarded. However, if you add a 'response' event handler,
then you must consume the data from the response object, either by
calling response.read() whenever there is a 'readable' event, or
by adding a 'data' handler, or by calling the .resume() method.
Until the data is consumed, the 'end' event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
Note: Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.
The request implements the Writable Stream interface. This is an
EventEmitter with the following events:
Event: 'abort'#
function () { }
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().
Event: 'checkExpectation'#
function (request, response) { }
Emitted each time a request with an http Expect header is received, where the value is not 100-continue. If this event isn't listened for, the server will automatically respond with a 417 Expectation Failed as appropriate.
Note that when this event is emitted and handled, the request event will
not be emitted.
Event: 'connect'#
function (response, socket, head) { }
Emitted each time a server responds to a request with a CONNECT method. If this
event isn't being listened for, clients receiving a CONNECT method will have
their connections closed.
A client server pair that show you how to listen for the 'connect' event.
const http = require('http');
const net = require('net');
const url = require('url');
// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server
var srvUrl = url.parse(`http://${req.url}`);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});
// now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// make a request to a tunneling proxy
var options = {
port: 1337,
hostname: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
var req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});
Event: 'continue'#
function () { }
Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
Event: 'response'#
function (response) { }
Emitted when a response is received to this request. This event is emitted only
once. The response argument will be an instance of http.IncomingMessage.
Event: 'socket'#
function (socket) { }
Emitted after a socket is assigned to this request.
Event: 'upgrade'#
function (response, socket, head) { }
Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
A client server pair that show you how to listen for the 'upgrade' event.
const http = require('http');
// Create an HTTP server
var srv = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
srv.on('upgrade', (req, socket, head) => {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// now that server is running
srv.listen(1337, '127.0.0.1', () => {
// make a request
var options = {
port: 1337,
hostname: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
var req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});
request.abort()#
Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.
request.end([data][, encoding][, callback])#
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n'.
If data is specified, it is equivalent to calling
response.write(data, encoding) followed by request.end(callback).
If callback is specified, it will be called when the request stream
is finished.
request.flushHeaders()#
Flush the request headers.
For efficiency reasons, Node.js normally buffers the request headers until you
call request.end() or write the first chunk of request data. It then tries
hard to pack the request headers and data into a single TCP packet.
That's usually what you want (it saves a TCP round-trip) but not when the first
data isn't sent until possibly much later. request.flushHeaders() lets you bypass
the optimization and kickstart the request.
request.setNoDelay([noDelay])#
Once a socket is assigned to this request and is connected
socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable][, initialDelay])#
Once a socket is assigned to this request and is connected
socket.setKeepAlive() will be called.
request.setTimeout(timeout[, callback])#
Once a socket is assigned to this request and is connected
socket.setTimeout() will be called.
timeout<Number> Milliseconds before a request is considered to be timed out.callback<Function> Optional function to be called when a timeout occurs. Same as binding to thetimeoutevent.
request.write(chunk[, encoding][, callback])#
Sends a chunk of the body. By calling this method
many times, the user can stream a request body to a
server--in that case it is suggested to use the
['Transfer-Encoding', 'chunked'] header line when
creating the request.
The chunk argument should be a Buffer or a string.
The encoding argument is optional and only applies when chunk is a string.
Defaults to 'utf8'.
The callback argument is optional and will be called when this chunk of data
is flushed.
Returns request.
Class: http.Server#
This class inherits from net.Server and has the following additional events:
Event: 'checkContinue'#
function (request, response) { }
Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate.
Handling this event involves calling response.writeContinue() if the client
should continue to send the request body, or generating an appropriate HTTP
response (e.g., 400 Bad Request) if the client should not continue to send the
request body.
Note that when this event is emitted and handled, the 'request' event will
not be emitted.
Event: 'clientError'#
function (exception, socket) { }
If a client connection emits an 'error' event, it will be forwarded here.
socket is the net.Socket object that the error originated from.
Event: 'close'#
function () { }
Emitted when the server closes.
Event: 'connect'#
function (request, socket, head) { }
Emitted each time a client requests a http CONNECT method. If this event isn't
listened for, then clients requesting a CONNECT method will have their
connections closed.
requestis the arguments for the http request, as it is in the request event.socketis the network socket between the server and client.headis an instance of Buffer, the first packet of the tunneling stream, this may be empty.
After this event is emitted, the request's socket will not have a 'data'
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.
Event: 'connection'#
function (socket) { }
When a new TCP stream is established. socket is an object of type
net.Socket. Usually users will not want to access this event. In
particular, the socket will not emit 'readable' events because of how
the protocol parser attaches to the socket. The socket can also be
accessed at request.connection.
Event: 'request'#
function (request, response) { }
Emitted each time there is a request. Note that there may be multiple requests
per connection (in the case of keep-alive connections).
request is an instance of http.IncomingMessage and response is
an instance of http.ServerResponse.