mirror of https://github.com/lukechilds/node.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1264 lines
41 KiB
1264 lines
41 KiB
13 years ago
|
# HTTP
|
||
14 years ago
|
|
||
10 years ago
|
Stability: 2 - Stable
|
||
13 years ago
|
|
||
14 years ago
|
To use the HTTP server and client one must `require('http')`.
|
||
|
|
||
10 years ago
|
The HTTP interfaces in Node.js are designed to support many features
|
||
14 years ago
|
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:
|
||
|
|
||
9 years ago
|
```
|
||
|
{ 'content-length': '123',
|
||
|
'content-type': 'text/plain',
|
||
|
'connection': 'keep-alive',
|
||
|
'host': 'mysite.com',
|
||
|
'accept': '*/*' }
|
||
|
```
|
||
14 years ago
|
|
||
|
Keys are lowercased. Values are not modified.
|
||
|
|
||
10 years ago
|
In order to support the full spectrum of possible HTTP applications, Node.js's
|
||
14 years ago
|
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.
|
||
|
|
||
9 years ago
|
See [`message.headers`][] for details on how duplicate headers are handled.
|
||
12 years ago
|
|
||
|
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:
|
||
|
|
||
9 years ago
|
```
|
||
|
[ 'ConTent-Length', '123456',
|
||
|
'content-LENGTH', '123',
|
||
|
'content-type', 'text/plain',
|
||
|
'CONNECTION', 'keep-alive',
|
||
|
'Host', 'mysite.com',
|
||
|
'accepT', '*/*' ]
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
## Class: http.Agent
|
||
14 years ago
|
|
||
9 years ago
|
The HTTP Agent is used for pooling sockets used in HTTP client
|
||
|
requests.
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
If you opt into using HTTP KeepAlive, you can create an Agent object
|
||
9 years ago
|
with that flag set to `true`. (See the [constructor options][].)
|
||
9 years ago
|
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.
|
||
13 years ago
|
|
||
9 years ago
|
Sockets are removed from the agent's pool when the socket emits either
|
||
9 years ago
|
a `'close'` event or a special `'agentRemove'` event. This means that if
|
||
9 years ago
|
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:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
http.get(options, (res) => {
|
||
|
// Do stuff
|
||
|
}).on('socket', (socket) => {
|
||
|
socket.emit('agentRemove');
|
||
|
});
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
Alternatively, you could just opt out of pooling entirely using
|
||
|
`agent:false`:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
http.get({
|
||
|
hostname: 'localhost',
|
||
|
port: 80,
|
||
|
path: '/',
|
||
|
agent: false // create a new agent just for this one request
|
||
|
}, (res) => {
|
||
|
// Do stuff with response
|
||
|
})
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
### new Agent([options])
|
||
14 years ago
|
|
||
9 years ago
|
* `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 = `false`
|
||
|
* `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`.
|
||
|
* `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 if `keepAlive` is set to `true`.
|
||
|
Default = `256`.
|
||
14 years ago
|
|
||
9 years ago
|
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
|
||
9 years ago
|
of these values set to their respective defaults.
|
||
13 years ago
|
|
||
9 years ago
|
To configure any of them, you must create your own [`http.Agent`][] object.
|
||
13 years ago
|
|
||
9 years ago
|
```js
|
||
9 years ago
|
const http = require('http');
|
||
9 years ago
|
var keepAliveAgent = new http.Agent({ keepAlive: true });
|
||
|
options.agent = keepAliveAgent;
|
||
|
http.request(options, onResponseCallback);
|
||
|
```
|
||
13 years ago
|
|
||
9 years ago
|
### 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)`.
|
||
|
|
||
9 years ago
|
### agent.destroy()
|
||
13 years ago
|
|
||
9 years ago
|
Destroy any sockets that are currently in use by the agent.
|
||
13 years ago
|
|
||
9 years ago
|
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.
|
||
13 years ago
|
|
||
9 years ago
|
### agent.freeSockets
|
||
14 years ago
|
|
||
9 years ago
|
An object which contains arrays of sockets currently awaiting use by
|
||
|
the Agent when HTTP KeepAlive is used. Do not modify.
|
||
14 years ago
|
|
||
9 years ago
|
### agent.getName(options)
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
13 years ago
|
|
||
9 years ago
|
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.
|
||
|
|
||
9 years ago
|
### agent.maxFreeSockets
|
||
13 years ago
|
|
||
9 years ago
|
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.
|
||
13 years ago
|
|
||
9 years ago
|
### agent.maxSockets
|
||
12 years ago
|
|
||
9 years ago
|
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.
|
||
12 years ago
|
|
||
9 years ago
|
### agent.requests
|
||
12 years ago
|
|
||
9 years ago
|
An object which contains queues of requests that have not yet been assigned to
|
||
|
sockets. Do not modify.
|
||
12 years ago
|
|
||
9 years ago
|
### agent.sockets
|
||
10 years ago
|
|
||
9 years ago
|
An object which contains arrays of sockets currently in use by the
|
||
|
Agent. Do not modify.
|
||
12 years ago
|
|
||
9 years ago
|
## Class: http.ClientRequest
|
||
12 years ago
|
|
||
9 years ago
|
This object is created internally and returned from [`http.request()`][]. It
|
||
9 years ago
|
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.
|
||
12 years ago
|
|
||
9 years ago
|
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
|
||
9 years ago
|
argument which is an instance of [`http.IncomingMessage`][].
|
||
12 years ago
|
|
||
9 years ago
|
During the `'response'` event, one can add listeners to the
|
||
|
response object; particularly to listen for the `'data'` event.
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
Note: Node.js does not check whether Content-Length and the length of the body
|
||
|
which has been transmitted are equal or not.
|
||
13 years ago
|
|
||
9 years ago
|
The request implements the [Writable Stream][] interface. This is an
|
||
9 years ago
|
[`EventEmitter`][] with the following events:
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'abort'
|
||
11 years ago
|
|
||
|
`function () { }`
|
||
|
|
||
9 years ago
|
Emitted when the request has been aborted by the client. This event is only
|
||
|
emitted on the first call to `abort()`.
|
||
14 years ago
|
|
||
9 years ago
|
### 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.
|
||
|
|
||
9 years ago
|
### Event: 'connect'
|
||
14 years ago
|
|
||
9 years ago
|
`function (response, socket, head) { }`
|
||
14 years ago
|
|
||
9 years ago
|
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
|
||
9 years ago
|
their connections closed.
|
||
14 years ago
|
|
||
9 years ago
|
A client server pair that show you how to listen for the `'connect'` event.
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
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());
|
||
9 years ago
|
});
|
||
9 years ago
|
socket.on('end', () => {
|
||
|
proxy.close();
|
||
9 years ago
|
});
|
||
9 years ago
|
});
|
||
|
});
|
||
|
```
|
||
12 years ago
|
|
||
9 years ago
|
### Event: 'continue'
|
||
12 years ago
|
|
||
9 years ago
|
`function () { }`
|
||
10 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'response'
|
||
14 years ago
|
|
||
9 years ago
|
`function (response) { }`
|
||
14 years ago
|
|
||
9 years ago
|
Emitted when a response is received to this request. This event is emitted only
|
||
9 years ago
|
once. The `response` argument will be an instance of [`http.IncomingMessage`][].
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'socket'
|
||
11 years ago
|
|
||
9 years ago
|
`function (socket) { }`
|
||
11 years ago
|
|
||
9 years ago
|
Emitted after a socket is assigned to this request.
|
||
11 years ago
|
|
||
9 years ago
|
### Event: 'upgrade'
|
||
11 years ago
|
|
||
9 years ago
|
`function (response, socket, head) { }`
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
A client server pair that show you how to listen for the `'upgrade'` event.
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
const http = require('http');
|
||
14 years ago
|
|
||
9 years ago
|
// 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);
|
||
|
});
|
||
|
});
|
||
|
```
|
||
13 years ago
|
|
||
9 years ago
|
### request.abort()
|
||
13 years ago
|
|
||
9 years ago
|
Marks the request as aborting. Calling this will cause remaining data
|
||
|
in the response to be dropped and the socket to be destroyed.
|
||
14 years ago
|
|
||
9 years ago
|
### request.end([data][, encoding][, callback])
|
||
14 years ago
|
|
||
9 years ago
|
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'`.
|
||
14 years ago
|
|
||
9 years ago
|
If `data` is specified, it is equivalent to calling
|
||
9 years ago
|
[`response.write(data, encoding)`][] followed by `request.end(callback)`.
|
||
14 years ago
|
|
||
9 years ago
|
If `callback` is specified, it will be called when the request stream
|
||
|
is finished.
|
||
14 years ago
|
|
||
9 years ago
|
### request.flushHeaders()
|
||
14 years ago
|
|
||
9 years ago
|
Flush the request headers.
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
### request.setNoDelay([noDelay])
|
||
14 years ago
|
|
||
9 years ago
|
Once a socket is assigned to this request and is connected
|
||
9 years ago
|
[`socket.setNoDelay()`][] will be called.
|
||
14 years ago
|
|
||
9 years ago
|
### request.setSocketKeepAlive([enable][, initialDelay])
|
||
14 years ago
|
|
||
9 years ago
|
Once a socket is assigned to this request and is connected
|
||
9 years ago
|
[`socket.setKeepAlive()`][] will be called.
|
||
14 years ago
|
|
||
9 years ago
|
### request.setTimeout(timeout[, callback])
|
||
14 years ago
|
|
||
9 years ago
|
Once a socket is assigned to this request and is connected
|
||
9 years ago
|
[`socket.setTimeout()`][] will be called.
|
||
14 years ago
|
|
||
9 years ago
|
* `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 the `timeout` event.
|
||
|
|
||
9 years ago
|
### request.write(chunk[, encoding][, callback])
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
13 years ago
|
|
||
9 years ago
|
The `chunk` argument should be a [`Buffer`][] or a string.
|
||
14 years ago
|
|
||
9 years ago
|
The `encoding` argument is optional and only applies when `chunk` is a string.
|
||
|
Defaults to `'utf8'`.
|
||
14 years ago
|
|
||
9 years ago
|
The `callback` argument is optional and will be called when this chunk of data
|
||
|
is flushed.
|
||
14 years ago
|
|
||
9 years ago
|
Returns `request`.
|
||
14 years ago
|
|
||
9 years ago
|
## Class: http.Server
|
||
14 years ago
|
|
||
9 years ago
|
This class inherits from [`net.Server`][] and has the following additional events:
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'checkContinue'
|
||
14 years ago
|
|
||
9 years ago
|
`function (request, response) { }`
|
||
14 years ago
|
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
Handling this event involves calling [`response.writeContinue()`][] if the client
|
||
9 years ago
|
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.
|
||
14 years ago
|
|
||
9 years ago
|
Note that when this event is emitted and handled, the `'request'` event will
|
||
9 years ago
|
not be emitted.
|
||
11 years ago
|
|
||
9 years ago
|
### Event: 'clientError'
|
||
11 years ago
|
|
||
9 years ago
|
`function (exception, socket) { }`
|
||
14 years ago
|
|
||
9 years ago
|
If a client connection emits an `'error'` event, it will be forwarded here.
|
||
9 years ago
|
Listener of this event is responsible for closing/destroying the underlying
|
||
|
socket. For example, one may wish to more gracefully close the socket with an
|
||
|
HTTP '400 Bad Request' response instead of abruptly severing the connection.
|
||
|
|
||
|
Default behavior is to destroy the socket immediately on malformed request.
|
||
13 years ago
|
|
||
9 years ago
|
`socket` is the [`net.Socket`][] object that the error originated from.
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
const http = require('http');
|
||
|
|
||
|
const server = http.createServer((req, res) => {
|
||
|
res.end();
|
||
|
});
|
||
|
server.on('clientError', (err, socket) => {
|
||
|
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
|
||
|
});
|
||
|
server.listen(8000);
|
||
|
```
|
||
|
|
||
|
When the `'clientError'` event occurs, there is no `request` or `response`
|
||
|
object, so any HTTP response sent, including response headers and payload,
|
||
|
*must* be written directly to the `socket` object. Care must be taken to
|
||
|
ensure the response is a properly formatted HTTP response message.
|
||
|
|
||
9 years ago
|
### Event: 'close'
|
||
14 years ago
|
|
||
9 years ago
|
`function () { }`
|
||
14 years ago
|
|
||
9 years ago
|
Emitted when the server closes.
|
||
11 years ago
|
|
||
9 years ago
|
### Event: 'connect'
|
||
14 years ago
|
|
||
9 years ago
|
`function (request, socket, head) { }`
|
||
14 years ago
|
|
||
9 years ago
|
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
|
||
9 years ago
|
connections closed.
|
||
10 years ago
|
|
||
9 years ago
|
* `request` is the arguments for the http request, as it is in the request
|
||
|
event.
|
||
|
* `socket` is the network socket between the server and client.
|
||
|
* `head` is an instance of Buffer, the first packet of the tunneling stream,
|
||
|
this may be empty.
|
||
14 years ago
|
|
||
9 years ago
|
After this event is emitted, the request's socket will not have a `'data'`
|
||
9 years ago
|
event listener, meaning you will need to bind to it in order to handle data
|
||
|
sent to the server on that socket.
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'connection'
|
||
14 years ago
|
|
||
9 years ago
|
`function (socket) { }`
|
||
14 years ago
|
|
||
9 years ago
|
When a new TCP stream is established. `socket` is an object of type
|
||
9 years ago
|
[`net.Socket`][]. Usually users will not want to access this event. In
|
||
|
particular, the socket will not emit `'readable'` events because of how
|
||
9 years ago
|
the protocol parser attaches to the socket. The `socket` can also be
|
||
|
accessed at `request.connection`.
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'request'
|
||
14 years ago
|
|
||
9 years ago
|
`function (request, response) { }`
|
||
14 years ago
|
|
||
9 years ago
|
Emitted each time there is a request. Note that there may be multiple requests
|
||
|
per connection (in the case of keep-alive connections).
|
||
9 years ago
|
`request` is an instance of [`http.IncomingMessage`][] and `response` is
|
||
|
an instance of [`http.ServerResponse`][].
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'upgrade'
|
||
14 years ago
|
|
||
9 years ago
|
`function (request, socket, head) { }`
|
||
14 years ago
|
|
||
9 years ago
|
Emitted each time a client requests a http upgrade. If this event isn't
|
||
|
listened for, then clients requesting an upgrade will have their connections
|
||
|
closed.
|
||
13 years ago
|
|
||
9 years ago
|
* `request` is the arguments for the http request, as it is in the request
|
||
|
event.
|
||
|
* `socket` is the network socket between the server and client.
|
||
|
* `head` is an instance of Buffer, the first packet of the upgraded stream,
|
||
|
this may be empty.
|
||
14 years ago
|
|
||
9 years ago
|
After this event is emitted, the request's socket will not have a `'data'`
|
||
9 years ago
|
event listener, meaning you will need to bind to it in order to handle data
|
||
|
sent to the server on that socket.
|
||
14 years ago
|
|
||
9 years ago
|
### server.close([callback])
|
||
14 years ago
|
|
||
9 years ago
|
Stops the server from accepting new connections. See [`net.Server.close()`][].
|
||
14 years ago
|
|
||
9 years ago
|
### server.listen(handle[, callback])
|
||
14 years ago
|
|
||
9 years ago
|
* `handle` {Object}
|
||
|
* `callback` {Function}
|
||
14 years ago
|
|
||
9 years ago
|
The `handle` object can be set to either a server or socket (anything
|
||
|
with an underlying `_handle` member), or a `{fd: <n>}` object.
|
||
14 years ago
|
|
||
9 years ago
|
This will cause the server to accept connections on the specified
|
||
|
handle, but it is presumed that the file descriptor or handle has
|
||
|
already been bound to a port or domain socket.
|
||
12 years ago
|
|
||
9 years ago
|
Listening on a file descriptor is not supported on Windows.
|
||
12 years ago
|
|
||
9 years ago
|
This function is asynchronous. The last parameter `callback` will be added as
|
||
9 years ago
|
a listener for the `'listening'` event. See also [`net.Server.listen()`][].
|
||
14 years ago
|
|
||
9 years ago
|
Returns `server`.
|
||
|
|
||
9 years ago
|
### server.listen(path[, callback])
|
||
13 years ago
|
|
||
9 years ago
|
Start a UNIX socket server listening for connections on the given `path`.
|
||
14 years ago
|
|
||
9 years ago
|
This function is asynchronous. The last parameter `callback` will be added as
|
||
9 years ago
|
a listener for the `'listening'` event. See also [`net.Server.listen(path)`][].
|
||
14 years ago
|
|
||
9 years ago
|
### server.listen(port[, hostname][, backlog][, callback])
|
||
12 years ago
|
|
||
9 years ago
|
Begin accepting connections on the specified `port` and `hostname`. If the
|
||
|
`hostname` is omitted, the server will accept connections on any IPv6 address
|
||
|
(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
|
||
|
port value of zero will assign a random port.
|
||
12 years ago
|
|
||
9 years ago
|
To listen to a unix socket, supply a filename instead of port and hostname.
|
||
12 years ago
|
|
||
9 years ago
|
Backlog is the maximum length of the queue of pending connections.
|
||
|
The actual length will be determined by your OS through sysctl settings such as
|
||
|
`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
|
||
|
parameter is 511 (not 512).
|
||
12 years ago
|
|
||
9 years ago
|
This function is asynchronous. The last parameter `callback` will be added as
|
||
9 years ago
|
a listener for the `'listening'` event. See also [`net.Server.listen(port)`][].
|
||
12 years ago
|
|
||
9 years ago
|
### server.listening
|
||
|
|
||
|
A Boolean indicating whether or not the server is listening for
|
||
|
connections.
|
||
|
|
||
9 years ago
|
### server.maxHeadersCount
|
||
14 years ago
|
|
||
9 years ago
|
Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
|
||
|
no limit will be applied.
|
||
12 years ago
|
|
||
9 years ago
|
### server.setTimeout(msecs, callback)
|
||
12 years ago
|
|
||
9 years ago
|
* `msecs` {Number}
|
||
|
* `callback` {Function}
|
||
14 years ago
|
|
||
9 years ago
|
Sets the timeout value for sockets, and emits a `'timeout'` event on
|
||
|
the Server object, passing the socket as an argument, if a timeout
|
||
|
occurs.
|
||
14 years ago
|
|
||
9 years ago
|
If there is a `'timeout'` event listener on the Server object, then it
|
||
|
will be called with the timed-out socket as an argument.
|
||
12 years ago
|
|
||
9 years ago
|
By default, the Server's timeout value is 2 minutes, and sockets are
|
||
|
destroyed automatically if they time out. However, if you assign a
|
||
|
callback to the Server's `'timeout'` event, then you are responsible
|
||
|
for handling socket timeouts.
|
||
12 years ago
|
|
||
9 years ago
|
Returns `server`.
|
||
14 years ago
|
|
||
9 years ago
|
### server.timeout
|
||
14 years ago
|
|
||
9 years ago
|
* {Number} Default = 120000 (2 minutes)
|
||
14 years ago
|
|
||
9 years ago
|
The number of milliseconds of inactivity before a socket is presumed
|
||
|
to have timed out.
|
||
12 years ago
|
|
||
9 years ago
|
Note that the socket timeout logic is set up on connection, so
|
||
|
changing this value only affects *new* connections to the server, not
|
||
|
any existing connections.
|
||
12 years ago
|
|
||
9 years ago
|
Set to 0 to disable any kind of automatic timeout behavior on incoming
|
||
|
connections.
|
||
12 years ago
|
|
||
9 years ago
|
## Class: http.ServerResponse
|
||
12 years ago
|
|
||
9 years ago
|
This object is created internally by a HTTP server--not by the user. It is
|
||
|
passed as the second parameter to the `'request'` event.
|
||
12 years ago
|
|
||
9 years ago
|
The response implements the [Writable Stream][] interface. This is an
|
||
9 years ago
|
[`EventEmitter`][] with the following events:
|
||
12 years ago
|
|
||
9 years ago
|
### Event: 'close'
|
||
13 years ago
|
|
||
9 years ago
|
`function () { }`
|
||
13 years ago
|
|
||
9 years ago
|
Indicates that the underlying connection was terminated before
|
||
9 years ago
|
[`response.end()`][] was called or able to flush.
|
||
14 years ago
|
|
||
9 years ago
|
### Event: 'finish'
|
||
14 years ago
|
|
||
9 years ago
|
`function () { }`
|
||
14 years ago
|
|
||
9 years ago
|
Emitted when the response has been sent. More specifically, this event is
|
||
|
emitted when the last segment of the response headers and body have been
|
||
|
handed off to the operating system for transmission over the network. It
|
||
|
does not imply that the client has received anything yet.
|
||
14 years ago
|
|
||
9 years ago
|
After this event, no more events will be emitted on the response object.
|
||
14 years ago
|
|
||
9 years ago
|
### response.addTrailers(headers)
|
||
14 years ago
|
|
||
9 years ago
|
This method adds HTTP trailing headers (a header but at the end of the
|
||
|
message) to the response.
|
||
14 years ago
|
|
||
9 years ago
|
Trailers will **only** be emitted if chunked encoding is used for the
|
||
|
response; if it is not (e.g., if the request was HTTP/1.0), they will
|
||
|
be silently discarded.
|
||
14 years ago
|
|
||
9 years ago
|
Note that HTTP requires the `Trailer` header to be sent if you intend to
|
||
|
emit trailers, with a list of the header fields in its value. E.g.,
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.writeHead(200, { 'Content-Type': 'text/plain',
|
||
|
'Trailer': 'Content-MD5' });
|
||
|
response.write(fileData);
|
||
|
response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
|
||
|
response.end();
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
Attempting to set a header field name or value that contains invalid characters
|
||
|
will result in a [`TypeError`][] being thrown.
|
||
14 years ago
|
|
||
9 years ago
|
### response.end([data][, encoding][, callback])
|
||
14 years ago
|
|
||
9 years ago
|
This method signals to the server that all of the response headers and body
|
||
|
have been sent; that server should consider this message complete.
|
||
9 years ago
|
The method, `response.end()`, MUST be called on each response.
|
||
14 years ago
|
|
||
9 years ago
|
If `data` is specified, it is equivalent to calling
|
||
9 years ago
|
[`response.write(data, encoding)`][] followed by `response.end(callback)`.
|
||
14 years ago
|
|
||
9 years ago
|
If `callback` is specified, it will be called when the response stream
|
||
|
is finished.
|
||
14 years ago
|
|
||
9 years ago
|
### response.finished
|
||
14 years ago
|
|
||
9 years ago
|
Boolean value that indicates whether the response has completed. Starts
|
||
9 years ago
|
as `false`. After [`response.end()`][] executes, the value will be `true`.
|
||
13 years ago
|
|
||
9 years ago
|
### response.getHeader(name)
|
||
13 years ago
|
|
||
9 years ago
|
Reads out a header that's already been queued but not sent to the client. Note
|
||
|
that the name is case insensitive. This can only be called before headers get
|
||
|
implicitly flushed.
|
||
13 years ago
|
|
||
9 years ago
|
Example:
|
||
13 years ago
|
|
||
9 years ago
|
```js
|
||
|
var contentType = response.getHeader('content-type');
|
||
|
```
|
||
13 years ago
|
|
||
9 years ago
|
### response.headersSent
|
||
13 years ago
|
|
||
9 years ago
|
Boolean (read-only). True if headers were sent, false otherwise.
|
||
13 years ago
|
|
||
9 years ago
|
### response.removeHeader(name)
|
||
13 years ago
|
|
||
9 years ago
|
Removes a header that's queued for implicit sending.
|
||
13 years ago
|
|
||
9 years ago
|
Example:
|
||
13 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.removeHeader('Content-Encoding');
|
||
|
```
|
||
13 years ago
|
|
||
9 years ago
|
### response.sendDate
|
||
14 years ago
|
|
||
9 years ago
|
When true, the Date header will be automatically generated and sent in
|
||
|
the response if it is not already present in the headers. Defaults to true.
|
||
14 years ago
|
|
||
9 years ago
|
This should only be disabled for testing; HTTP requires the Date header
|
||
|
in responses.
|
||
14 years ago
|
|
||
9 years ago
|
### response.setHeader(name, value)
|
||
14 years ago
|
|
||
9 years ago
|
Sets a single header value for implicit headers. If this header already exists
|
||
|
in the to-be-sent headers, its value will be replaced. Use an array of strings
|
||
|
here if you need to send multiple headers with the same name.
|
||
14 years ago
|
|
||
9 years ago
|
Example:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.setHeader('Content-Type', 'text/html');
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
or
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
Attempting to set a header field name or value that contains invalid characters
|
||
|
will result in a [`TypeError`][] being thrown.
|
||
14 years ago
|
|
||
9 years ago
|
When headers have been set with [`response.setHeader()`][], they will be merged with
|
||
|
any headers passed to [`response.writeHead()`][], with the headers passed to
|
||
|
[`response.writeHead()`][] given precedence.
|
||
|
|
||
|
```js
|
||
|
// returns content-type = text/plain
|
||
|
const server = http.createServer((req,res) => {
|
||
|
res.setHeader('Content-Type', 'text/html');
|
||
|
res.setHeader('X-Foo', 'bar');
|
||
|
res.writeHead(200, {'Content-Type': 'text/plain'});
|
||
|
res.end('ok');
|
||
|
});
|
||
|
```
|
||
|
|
||
9 years ago
|
### response.setTimeout(msecs, callback)
|
||
14 years ago
|
|
||
9 years ago
|
* `msecs` {Number}
|
||
|
* `callback` {Function}
|
||
14 years ago
|
|
||
9 years ago
|
Sets the Socket's timeout value to `msecs`. If a callback is
|
||
|
provided, then it is added as a listener on the `'timeout'` event on
|
||
|
the response object.
|
||
14 years ago
|
|
||
9 years ago
|
If no `'timeout'` listener is added to the request, the response, or
|
||
|
the server, then sockets are destroyed when they time out. If you
|
||
|
assign a handler on the request, the response, or the server's
|
||
|
`'timeout'` events, then it is your responsibility to handle timed out
|
||
|
sockets.
|
||
14 years ago
|
|
||
9 years ago
|
Returns `response`.
|
||
10 years ago
|
|
||
9 years ago
|
### response.statusCode
|
||
10 years ago
|
|
||
9 years ago
|
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
|
||
9 years ago
|
this property controls the status code that will be sent to the client when
|
||
|
the headers get flushed.
|
||
10 years ago
|
|
||
9 years ago
|
Example:
|
||
11 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.statusCode = 404;
|
||
|
```
|
||
11 years ago
|
|
||
9 years ago
|
After response header was sent to the client, this property indicates the
|
||
|
status code which was sent out.
|
||
11 years ago
|
|
||
9 years ago
|
### response.statusMessage
|
||
11 years ago
|
|
||
9 years ago
|
When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property
|
||
9 years ago
|
controls the status message that will be sent to the client when the headers get
|
||
|
flushed. If this is left as `undefined` then the standard message for the status
|
||
|
code will be used.
|
||
14 years ago
|
|
||
9 years ago
|
Example:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
response.statusMessage = 'Not found';
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
After response header was sent to the client, this property indicates the
|
||
|
status message which was sent out.
|
||
14 years ago
|
|
||
9 years ago
|
### response.write(chunk[, encoding][, callback])
|
||
14 years ago
|
|
||
9 years ago
|
If this method is called and [`response.writeHead()`][] has not been called,
|
||
9 years ago
|
it will switch to implicit header mode and flush the implicit headers.
|
||
14 years ago
|
|
||
9 years ago
|
This sends a chunk of the response body. This method may
|
||
|
be called multiple times to provide successive parts of the body.
|
||
|
|
||
|
`chunk` can be a string or a buffer. If `chunk` is a string,
|
||
|
the second parameter specifies how to encode it into a byte stream.
|
||
|
By default the `encoding` is `'utf8'`. The last parameter `callback`
|
||
|
will be called when this chunk of data is flushed.
|
||
14 years ago
|
|
||
9 years ago
|
**Note**: This is the raw HTTP body and has nothing to do with
|
||
|
higher-level multi-part body encodings that may be used.
|
||
14 years ago
|
|
||
9 years ago
|
The first time [`response.write()`][] is called, it will send the buffered
|
||
9 years ago
|
header information and the first body to the client. The second time
|
||
9 years ago
|
[`response.write()`][] is called, Node.js assumes you're going to be streaming
|
||
9 years ago
|
data, and sends that separately. That is, the response is buffered up to the
|
||
|
first chunk of body.
|
||
10 years ago
|
|
||
9 years ago
|
Returns `true` if the entire data was flushed successfully to the kernel
|
||
|
buffer. Returns `false` if all or part of the data was queued in user memory.
|
||
|
`'drain'` will be emitted when the buffer is free again.
|
||
14 years ago
|
|
||
9 years ago
|
### response.writeContinue()
|
||
14 years ago
|
|
||
9 years ago
|
Sends a HTTP/1.1 100 Continue message to the client, indicating that
|
||
9 years ago
|
the request body should be sent. See the [`'checkContinue'`][] event on `Server`.
|
||
14 years ago
|
|
||
9 years ago
|
### response.writeHead(statusCode[, statusMessage][, headers])
|
||
14 years ago
|
|
||
9 years ago
|
Sends a response header to the request. The status code is a 3-digit HTTP
|
||
|
status code, like `404`. The last argument, `headers`, are the response headers.
|
||
|
Optionally one can give a human-readable `statusMessage` as the second
|
||
|
argument.
|
||
10 years ago
|
|
||
9 years ago
|
Example:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
var body = 'hello world';
|
||
|
response.writeHead(200, {
|
||
|
'Content-Length': body.length,
|
||
|
'Content-Type': 'text/plain' });
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
This method must only be called once on a message and it must
|
||
9 years ago
|
be called before [`response.end()`][] is called.
|
||
14 years ago
|
|
||
9 years ago
|
If you call [`response.write()`][] or [`response.end()`][] before calling this,
|
||
|
the implicit/mutable headers will be calculated and call this function for you.
|
||
14 years ago
|
|
||
9 years ago
|
When headers have been set with [`response.setHeader()`][], they will be merged with
|
||
|
any headers passed to [`response.writeHead()`][], with the headers passed to
|
||
|
[`response.writeHead()`][] given precedence.
|
||
|
|
||
|
```js
|
||
|
// returns content-type = text/plain
|
||
|
const server = http.createServer((req,res) => {
|
||
|
res.setHeader('Content-Type', 'text/html');
|
||
|
res.setHeader('X-Foo', 'bar');
|
||
|
res.writeHead(200, {'Content-Type': 'text/plain'});
|
||
|
res.end('ok');
|
||
|
});
|
||
|
```
|
||
|
|
||
9 years ago
|
Note that Content-Length is given in bytes not characters. The above example
|
||
|
works because the string `'hello world'` contains only single byte characters.
|
||
|
If the body contains higher coded characters then `Buffer.byteLength()`
|
||
|
should be used to determine the number of bytes in a given encoding.
|
||
|
And Node.js does not check whether Content-Length and the length of the body
|
||
|
which has been transmitted are equal or not.
|
||
14 years ago
|
|
||
9 years ago
|
Attempting to set a header field name or value that contains invalid characters
|
||
|
will result in a [`TypeError`][] being thrown.
|
||
|
|
||
9 years ago
|
## Class: http.IncomingMessage
|
||
14 years ago
|
|
||
9 years ago
|
An `IncomingMessage` object is created by [`http.Server`][] or
|
||
|
[`http.ClientRequest`][] and passed as the first argument to the `'request'`
|
||
11 years ago
|
and `'response'` event respectively. It may be used to access response status,
|
||
|
headers and data.
|
||
13 years ago
|
|
||
12 years ago
|
It implements the [Readable Stream][] interface, as well as the
|
||
|
following additional events, methods, and properties.
|
||
12 years ago
|
|
||
14 years ago
|
### Event: 'close'
|
||
|
|
||
12 years ago
|
`function () { }`
|
||
14 years ago
|
|
||
12 years ago
|
Indicates that the underlying connection was closed.
|
||
11 years ago
|
Just like `'end'`, this event occurs only once per response.
|
||
12 years ago
|
|
||
12 years ago
|
### message.headers
|
||
14 years ago
|
|
||
12 years ago
|
The request/response headers object.
|
||
14 years ago
|
|
||
9 years ago
|
Key-value pairs of header names and values. Header names are lower-cased.
|
||
12 years ago
|
Example:
|
||
14 years ago
|
|
||
9 years ago
|
```js
|
||
|
// Prints something like:
|
||
|
//
|
||
|
// { 'user-agent': 'curl/7.22.0',
|
||
|
// host: '127.0.0.1:8000',
|
||
|
// accept: '*/*' }
|
||
|
console.log(request.headers);
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
Duplicates in raw headers are handled in the following ways, depending on the
|
||
|
header name:
|
||
|
|
||
|
* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
|
||
|
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
|
||
|
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
|
||
|
`retry-after`, or `user-agent` are discarded.
|
||
|
* `set-cookie` is always an array. Duplicates are added to the array.
|
||
|
* For all other headers, the values are joined together with ', '.
|
||
|
|
||
9 years ago
|
### message.httpVersion
|
||
|
|
||
|
In case of server request, the HTTP version sent by the client. In the case of
|
||
|
client response, the HTTP version of the connected-to server.
|
||
|
Probably either `'1.1'` or `'1.0'`.
|
||
|
|
||
9 years ago
|
Also `message.httpVersionMajor` is the first integer and
|
||
|
`message.httpVersionMinor` is the second.
|
||
9 years ago
|
|
||
|
### message.method
|
||
|
|
||
9 years ago
|
**Only valid for request obtained from [`http.Server`][].**
|
||
9 years ago
|
|
||
|
The request method as a string. Read only. Example:
|
||
|
`'GET'`, `'DELETE'`.
|
||
|
|
||
12 years ago
|
### message.rawHeaders
|
||
|
|
||
|
The raw request/response headers list exactly as they were received.
|
||
|
|
||
|
Note that the keys and values are in the same list. It is *not* a
|
||
|
list of tuples. So, the even-numbered offsets are key values, and the
|
||
|
odd-numbered offsets are the associated values.
|
||
|
|
||
|
Header names are not lowercased, and duplicates are not merged.
|
||
|
|
||
9 years ago
|
```js
|
||
|
// Prints something like:
|
||
|
//
|
||
|
// [ 'user-agent',
|
||
|
// 'this is invalid because there can be only one',
|
||
|
// 'User-Agent',
|
||
|
// 'curl/7.22.0',
|
||
|
// 'Host',
|
||
|
// '127.0.0.1:8000',
|
||
|
// 'ACCEPT',
|
||
|
// '*/*' ]
|
||
|
console.log(request.rawHeaders);
|
||
|
```
|
||
12 years ago
|
|
||
|
### message.rawTrailers
|
||
|
|
||
|
The raw request/response trailer keys and values exactly as they were
|
||
9 years ago
|
received. Only populated at the `'end'` event.
|
||
12 years ago
|
|
||
12 years ago
|
### message.setTimeout(msecs, callback)
|
||
|
|
||
|
* `msecs` {Number}
|
||
|
* `callback` {Function}
|
||
|
|
||
|
Calls `message.connection.setTimeout(msecs, callback)`.
|
||
|
|
||
10 years ago
|
Returns `message`.
|
||
|
|
||
9 years ago
|
### message.statusCode
|
||
12 years ago
|
|
||
9 years ago
|
**Only valid for response obtained from [`http.ClientRequest`][].**
|
||
12 years ago
|
|
||
9 years ago
|
The 3-digit HTTP response status code. E.G. `404`.
|
||
|
|
||
|
### message.statusMessage
|
||
|
|
||
9 years ago
|
**Only valid for response obtained from [`http.ClientRequest`][].**
|
||
9 years ago
|
|
||
9 years ago
|
The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
|
||
|
|
||
9 years ago
|
### message.socket
|
||
|
|
||
9 years ago
|
The [`net.Socket`][] object associated with the connection.
|
||
9 years ago
|
|
||
9 years ago
|
With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
|
||
9 years ago
|
client's authentication details.
|
||
|
|
||
|
### message.trailers
|
||
|
|
||
9 years ago
|
The request/response trailers object. Only populated at the `'end'` event.
|
||
12 years ago
|
|
||
|
### message.url
|
||
|
|
||
9 years ago
|
**Only valid for request obtained from [`http.Server`][].**
|
||
12 years ago
|
|
||
|
Request URL string. This contains only the URL that is
|
||
|
present in the actual HTTP request. If the request is:
|
||
|
|
||
9 years ago
|
```
|
||
|
GET /status?name=ryan HTTP/1.1\r\n
|
||
|
Accept: text/plain\r\n
|
||
|
\r\n
|
||
|
```
|
||
12 years ago
|
|
||
|
Then `request.url` will be:
|
||
|
|
||
9 years ago
|
```
|
||
|
'/status?name=ryan'
|
||
|
```
|
||
12 years ago
|
|
||
|
If you would like to parse the URL into its parts, you can use
|
||
|
`require('url').parse(request.url)`. Example:
|
||
|
|
||
9 years ago
|
```
|
||
9 years ago
|
$ node
|
||
|
> require('url').parse('/status?name=ryan')
|
||
9 years ago
|
{
|
||
|
href: '/status?name=ryan',
|
||
|
search: '?name=ryan',
|
||
|
query: 'name=ryan',
|
||
|
pathname: '/status'
|
||
|
}
|
||
|
```
|
||
12 years ago
|
|
||
|
If you would like to extract the params from the query string,
|
||
|
you can use the `require('querystring').parse` function, or pass
|
||
|
`true` as the second argument to `require('url').parse`. Example:
|
||
14 years ago
|
|
||
9 years ago
|
```
|
||
9 years ago
|
$ node
|
||
|
> require('url').parse('/status?name=ryan', true)
|
||
9 years ago
|
{
|
||
|
href: '/status?name=ryan',
|
||
|
search: '?name=ryan',
|
||
|
query: {name: 'ryan'},
|
||
|
pathname: '/status'
|
||
|
}
|
||
|
```
|
||
14 years ago
|
|
||
9 years ago
|
## http.METHODS
|
||
12 years ago
|
|
||
9 years ago
|
* {Array}
|
||
12 years ago
|
|
||
9 years ago
|
A list of the HTTP methods that are supported by the parser.
|
||
12 years ago
|
|
||
9 years ago
|
## http.STATUS_CODES
|
||
11 years ago
|
|
||
9 years ago
|
* {Object}
|
||
11 years ago
|
|
||
9 years ago
|
A collection of all the standard HTTP response status codes, and the
|
||
|
short description of each. For example, `http.STATUS_CODES[404] === 'Not
|
||
|
Found'`.
|
||
11 years ago
|
|
||
9 years ago
|
## http.createClient([port][, host])
|
||
12 years ago
|
|
||
9 years ago
|
Stability: 0 - Deprecated: Use [`http.request()`][] instead.
|
||
12 years ago
|
|
||
9 years ago
|
Constructs a new HTTP client. `port` and `host` refer to the server to be
|
||
|
connected to.
|
||
14 years ago
|
|
||
9 years ago
|
## http.createServer([requestListener])
|
||
|
|
||
9 years ago
|
Returns a new instance of [`http.Server`][].
|
||
9 years ago
|
|
||
|
The `requestListener` is a function which is automatically
|
||
|
added to the `'request'` event.
|
||
|
|
||
|
## http.get(options[, callback])
|
||
|
|
||
|
Since most requests are GET requests without bodies, Node.js provides this
|
||
9 years ago
|
convenience method. The only difference between this method and [`http.request()`][]
|
||
9 years ago
|
is that it sets the method to GET and calls `req.end()` automatically.
|
||
|
|
||
|
Example:
|
||
|
|
||
9 years ago
|
```js
|
||
|
http.get('http://www.google.com/index.html', (res) => {
|
||
|
console.log(`Got response: ${res.statusCode}`);
|
||
|
// consume response body
|
||
|
res.resume();
|
||
|
}).on('error', (e) => {
|
||
|
console.log(`Got error: ${e.message}`);
|
||
|
});
|
||
|
```
|
||
9 years ago
|
|
||
|
## http.globalAgent
|
||
|
|
||
|
Global instance of Agent which is used as the default for all http client
|
||
|
requests.
|
||
|
|
||
|
## http.request(options[, callback])
|
||
|
|
||
|
Node.js maintains several connections per server to make HTTP requests.
|
||
|
This function allows one to transparently issue requests.
|
||
|
|
||
|
`options` can be an object or a string. If `options` is a string, it is
|
||
9 years ago
|
automatically parsed with [`url.parse()`][].
|
||
9 years ago
|
|
||
|
Options:
|
||
|
|
||
9 years ago
|
- `protocol`: Protocol to use. Defaults to `'http:'`.
|
||
9 years ago
|
- `host`: A domain name or IP address of the server to issue the request to.
|
||
|
Defaults to `'localhost'`.
|
||
9 years ago
|
- `hostname`: Alias for `host`. To support [`url.parse()`][] `hostname` is
|
||
9 years ago
|
preferred over `host`.
|
||
|
- `family`: 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.
|
||
|
- `port`: Port of remote server. Defaults to 80.
|
||
|
- `localAddress`: Local interface to bind for network connections.
|
||
|
- `socketPath`: Unix Domain Socket (use one of host:port or socketPath).
|
||
|
- `method`: A string specifying the HTTP request method. Defaults to `'GET'`.
|
||
|
- `path`: 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.
|
||
|
- `headers`: An object containing request headers.
|
||
|
- `auth`: Basic authentication i.e. `'user:password'` to compute an
|
||
|
Authorization header.
|
||
9 years ago
|
- `agent`: Controls [`Agent`][] behavior. When an Agent is used request will
|
||
9 years ago
|
default to `Connection: keep-alive`. Possible values:
|
||
9 years ago
|
- `undefined` (default): use [`http.globalAgent`][] for this host and port.
|
||
9 years ago
|
- `Agent` object: explicitly use the passed in `Agent`.
|
||
|
- `false`: opts out of connection pooling with an Agent, defaults request to
|
||
|
`Connection: close`.
|
||
9 years ago
|
- `createConnection`: 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.
|
||
9 years ago
|
|
||
|
The optional `callback` parameter will be added as a one time listener for
|
||
9 years ago
|
the `'response'` event.
|
||
9 years ago
|
|
||
9 years ago
|
`http.request()` returns an instance of the [`http.ClientRequest`][]
|
||
9 years ago
|
class. The `ClientRequest` instance is a writable stream. If one needs to
|
||
|
upload a file with a POST request, then write to the `ClientRequest` object.
|
||
|
|
||
|
Example:
|
||
|
|
||
9 years ago
|
```js
|
||
|
var postData = querystring.stringify({
|
||
|
'msg' : 'Hello World!'
|
||
|
});
|
||
|
|
||
|
var options = {
|
||
|
hostname: 'www.google.com',
|
||
|
port: 80,
|
||
|
path: '/upload',
|
||
|
method: 'POST',
|
||
|
headers: {
|
||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||
|
'Content-Length': postData.length
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var req = http.request(options, (res) => {
|
||
|
console.log(`STATUS: ${res.statusCode}`);
|
||
|
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
|
||
|
res.setEncoding('utf8');
|
||
|
res.on('data', (chunk) => {
|
||
|
console.log(`BODY: ${chunk}`);
|
||
|
});
|
||
|
res.on('end', () => {
|
||
|
console.log('No more data in response.')
|
||
|
})
|
||
|
});
|
||
|
|
||
|
req.on('error', (e) => {
|
||
|
console.log(`problem with request: ${e.message}`);
|
||
|
});
|
||
|
|
||
|
// write data to request body
|
||
|
req.write(postData);
|
||
|
req.end();
|
||
|
```
|
||
9 years ago
|
|
||
|
Note that in the example `req.end()` was called. With `http.request()` one
|
||
|
must always call `req.end()` to signify that you're done with the request -
|
||
|
even if there is no data being written to the request body.
|
||
|
|
||
|
If any error is encountered during the request (be that with DNS resolution,
|
||
|
TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
|
||
9 years ago
|
on the returned request object. As with all `'error'` events, if no listeners
|
||
|
are registered the error will be thrown.
|
||
9 years ago
|
|
||
|
There are a few special headers that should be noted.
|
||
|
|
||
|
* Sending a 'Connection: keep-alive' will notify Node.js that the connection to
|
||
|
the server should be persisted until the next request.
|
||
|
|
||
|
* Sending a 'Content-length' header will disable the default chunked encoding.
|
||
|
|
||
|
* Sending an 'Expect' header will immediately send the request headers.
|
||
|
Usually, when sending 'Expect: 100-continue', you should both set a timeout
|
||
9 years ago
|
and listen for the `'continue'` event. See RFC2616 Section 8.2.3 for more
|
||
9 years ago
|
information.
|
||
|
|
||
|
* Sending an Authorization header will override using the `auth` option
|
||
|
to compute basic authentication.
|
||
13 years ago
|
|
||
9 years ago
|
[`'checkContinue'`]: #http_event_checkcontinue
|
||
|
[`'listening'`]: net.html#net_event_listening
|
||
|
[`'response'`]: #http_event_response
|
||
|
[`Agent`]: #http_class_http_agent
|
||
9 years ago
|
[`agent.createConnection()`]: #http_agent_createconnection_options_callback
|
||
9 years ago
|
[`Buffer`]: buffer.html#buffer_buffer
|
||
9 years ago
|
[`destroy()`]: #http_agent_destroy
|
||
9 years ago
|
[`EventEmitter`]: events.html#events_class_eventemitter
|
||
9 years ago
|
[`http.Agent`]: #http_class_http_agent
|
||
|
[`http.ClientRequest`]: #http_class_http_clientrequest
|
||
|
[`http.globalAgent`]: #http_http_globalagent
|
||
9 years ago
|
[`http.IncomingMessage`]: #http_class_http_incomingmessage
|
||
9 years ago
|
[`http.request()`]: #http_http_request_options_callback
|
||
|
[`http.Server`]: #http_class_http_server
|
||
|
[`http.ServerResponse`]: #http_class_http_serverresponse
|
||
|
[`message.headers`]: #http_message_headers
|
||
9 years ago
|
[`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener
|
||
9 years ago
|
[`net.Server`]: net.html#net_class_net_server
|
||
9 years ago
|
[`net.Server.close()`]: net.html#net_server_close_callback
|
||
9 years ago
|
[`net.Server.listen()`]: net.html#net_server_listen_handle_backlog_callback
|
||
|
[`net.Server.listen(path)`]: net.html#net_server_listen_path_backlog_callback
|
||
9 years ago
|
[`net.Server.listen(port)`]: net.html#net_server_listen_port_hostname_backlog_callback
|
||
|
[`net.Socket`]: net.html#net_class_net_socket
|
||
|
[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
|
||
|
[`response.end()`]: #http_response_end_data_encoding_callback
|
||
9 years ago
|
[`response.setHeader()`]: #http_response_setheader_name_value
|
||
9 years ago
|
[`response.write()`]: #http_response_write_chunk_encoding_callback
|
||
|
[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
|
||
|
[`response.writeContinue()`]: #http_response_writecontinue
|
||
|
[`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
|
||
|
[`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
|
||
|
[`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
|
||
|
[`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
|
||
|
[`stream.setEncoding()`]: stream.html#stream_stream_setencoding_encoding
|
||
|
[`TypeError`]: errors.html#errors_class_typeerror
|
||
|
[`url.parse()`]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
|
||
|
[constructor options]: #http_new_agent_options
|
||
11 years ago
|
[Readable Stream]: stream.html#stream_class_stream_readable
|
||
|
[Writable Stream]: stream.html#stream_class_stream_writable
|