Skip to content

Latest commit

Β 

History

History
963 lines (672 loc) Β· 31.6 KB

File metadata and controls

963 lines (672 loc) Β· 31.6 KB
Β 
Feb 27, 2012
Feb 27, 2012
1
# HTTP
Oct 28, 2010
Oct 28, 2010
2
Mar 4, 2012
Mar 4, 2012
3
Stability: 3 - Stable
4
Oct 28, 2010
Oct 28, 2010
5
To use the HTTP server and client one must `require('http')`.
6
7
The HTTP interfaces in Node are designed to support many features
8
of the protocol which have been traditionally difficult to use.
9
In particular, large, possibly chunk-encoded, messages. The interface is
10
careful to never buffer entire requests or responses--the
11
user is able to stream data.
12
13
HTTP message headers are represented by an object like this:
14
Nov 18, 2010
Nov 18, 2010
15
{ 'content-length': '123',
16
'content-type': 'text/plain',
17
'connection': 'keep-alive',
18
'accept': '*/*' }
Oct 28, 2010
Oct 28, 2010
19
20
Keys are lowercased. Values are not modified.
21
22
In order to support the full spectrum of possible HTTP applications, Node's
23
HTTP API is very low-level. It deals with stream handling and message
24
parsing only. It parses a message into headers and body but it does not
25
parse the actual headers or the body.
26
27
May 6, 2012
May 6, 2012
28
## http.STATUS_CODES
29
30
* {Object}
31
32
A collection of all the standard HTTP response status codes, and the
33
short description of each. For example, `http.STATUS_CODES[404] === 'Not
34
Found'`.
35
Feb 27, 2012
Feb 27, 2012
36
## http.createServer([requestListener])
37
38
Returns a new web server object.
39
40
The `requestListener` is a function which is automatically
41
added to the `'request'` event.
42
Apr 23, 2012
Apr 23, 2012
43
## http.createClient([port], [host])
44
Jun 15, 2012
Jun 15, 2012
45
This function is **deprecated**; please use [http.request()][] instead.
46
Constructs a new HTTP client. `port` and `host` refer to the server to be
47
connected to.
Apr 23, 2012
Apr 23, 2012
48
Feb 27, 2012
Feb 27, 2012
49
## Class: http.Server
Oct 28, 2010
Oct 28, 2010
50
Jun 15, 2012
Jun 15, 2012
51
This is an [EventEmitter][] with the following events:
Oct 28, 2010
Oct 28, 2010
52
53
### Event: 'request'
54
55
`function (request, response) { }`
56
Sep 6, 2011
Sep 6, 2011
57
Emitted each time there is a request. Note that there may be multiple requests
Apr 12, 2011
Apr 12, 2011
58
per connection (in the case of keep-alive connections).
Feb 7, 2013
Feb 7, 2013
59
`request` is an instance of `http.IncomingMessage` and `response` is
Oct 28, 2010
Oct 28, 2010
60
an instance of `http.ServerResponse`
61
62
### Event: 'connection'
63
Jul 16, 2011
Jul 16, 2011
64
`function (socket) { }`
Oct 28, 2010
Oct 28, 2010
65
Jul 16, 2011
Jul 16, 2011
66
When a new TCP stream is established. `socket` is an object of type
Apr 16, 2013
Apr 16, 2013
67
`net.Socket`. Usually users will not want to access this event. In
68
particular, the socket will not emit `readable` events because of how
69
the protocol parser attaches to the socket. The `socket` can also be
70
accessed at `request.connection`.
Oct 28, 2010
Oct 28, 2010
71
72
### Event: 'close'
73
Nov 2, 2011
Nov 2, 2011
74
`function () { }`
Oct 28, 2010
Oct 28, 2010
75
Nov 21, 2010
Nov 21, 2010
76
Emitted when the server closes.
Oct 28, 2010
Oct 28, 2010
77
78
### Event: 'checkContinue'
79
Jul 9, 2011
Jul 9, 2011
80
`function (request, response) { }`
Oct 28, 2010
Oct 28, 2010
81
82
Emitted each time a request with an http Expect: 100-continue is received.
83
If this event isn't listened for, the server will automatically respond
84
with a 100 Continue as appropriate.
85
86
Handling this event involves calling `response.writeContinue` if the client
87
should continue to send the request body, or generating an appropriate HTTP
88
response (e.g., 400 Bad Request) if the client should not continue to send the
89
request body.
90
91
Note that when this event is emitted and handled, the `request` event will
92
not be emitted.
93
Jan 9, 2012
Jan 9, 2012
94
### Event: 'connect'
95
Jun 13, 2013
Jun 13, 2013
96
`function (request, socket, head) { }`
Jan 9, 2012
Jan 9, 2012
97
98
Emitted each time a client requests a http CONNECT method. If this event isn't
99
listened for, then clients requesting a CONNECT method will have their
100
connections closed.
101
102
* `request` is the arguments for the http request, as it is in the request
103
event.
104
* `socket` is the network socket between the server and client.
Jun 13, 2013
Jun 13, 2013
105
* `head` is an instance of Buffer, the first packet of the tunneling stream,
106
this may be empty.
Jan 9, 2012
Jan 9, 2012
107
108
After this event is emitted, the request's socket will not have a `data`
109
event listener, meaning you will need to bind to it in order to handle data
110
sent to the server on that socket.
111
Oct 28, 2010
Oct 28, 2010
112
### Event: 'upgrade'
113
Jun 13, 2013
Jun 13, 2013
114
`function (request, socket, head) { }`
Oct 28, 2010
Oct 28, 2010
115
116
Emitted each time a client requests a http upgrade. If this event isn't
117
listened for, then clients requesting an upgrade will have their connections
118
closed.
119
Jan 9, 2012
Jan 9, 2012
120
* `request` is the arguments for the http request, as it is in the request
121
event.
Oct 28, 2010
Oct 28, 2010
122
* `socket` is the network socket between the server and client.
Jun 13, 2013
Jun 13, 2013
123
* `head` is an instance of Buffer, the first packet of the upgraded stream,
124
this may be empty.
Oct 28, 2010
Oct 28, 2010
125
126
After this event is emitted, the request's socket will not have a `data`
127
event listener, meaning you will need to bind to it in order to handle data
128
sent to the server on that socket.
129
130
### Event: 'clientError'
131
Oct 9, 2012
Oct 9, 2012
132
`function (exception, socket) { }`
Oct 28, 2010
Oct 28, 2010
133
134
If a client connection emits an 'error' event - it will forwarded here.
135
Oct 9, 2012
Oct 9, 2012
136
`socket` is the `net.Socket` object that the error originated from.
137
138
Apr 18, 2012
Apr 18, 2012
139
### server.listen(port, [hostname], [backlog], [callback])
Oct 28, 2010
Oct 28, 2010
140
141
Begin accepting connections on the specified port and hostname. If the
142
hostname is omitted, the server will accept connections directed to any
143
IPv4 address (`INADDR_ANY`).
144
145
To listen to a unix socket, supply a filename instead of port and hostname.
146
Apr 18, 2012
Apr 18, 2012
147
Backlog is the maximum length of the queue of pending connections.
148
The actual length will be determined by your OS through sysctl settings such as
149
`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
150
parameter is 511 (not 512).
151
Dec 16, 2011
Dec 16, 2011
152
This function is asynchronous. The last parameter `callback` will be added as
Jun 15, 2012
Jun 15, 2012
153
a listener for the ['listening'][] event. See also [net.Server.listen(port)][].
Oct 28, 2010
Oct 28, 2010
154
155
156
### server.listen(path, [callback])
157
158
Start a UNIX socket server listening for connections on the given `path`.
159
Dec 16, 2011
Dec 16, 2011
160
This function is asynchronous. The last parameter `callback` will be added as
Jun 15, 2012
Jun 15, 2012
161
a listener for the ['listening'][] event. See also [net.Server.listen(path)][].
Oct 28, 2010
Oct 28, 2010
162
163
Oct 8, 2012
Oct 8, 2012
164
### server.listen(handle, [callback])
Jun 13, 2012
Jun 13, 2012
165
166
* `handle` {Object}
Oct 8, 2012
Oct 8, 2012
167
* `callback` {Function}
Jun 13, 2012
Jun 13, 2012
168
169
The `handle` object can be set to either a server or socket (anything
170
with an underlying `_handle` member), or a `{fd: <n>}` object.
171
172
This will cause the server to accept connections on the specified
173
handle, but it is presumed that the file descriptor or handle has
174
already been bound to a port or domain socket.
175
176
Listening on a file descriptor is not supported on Windows.
177
178
This function is asynchronous. The last parameter `callback` will be added as
179
a listener for the ['listening'](net.html#event_listening_) event.
Oct 8, 2012
Oct 8, 2012
180
See also [net.Server.listen()](net.html#net_server_listen_handle_callback).
Jun 13, 2012
Jun 13, 2012
181
Oct 8, 2012
Oct 8, 2012
182
### server.close([callback])
Oct 28, 2010
Oct 28, 2010
183
Jun 15, 2012
Jun 15, 2012
184
Stops the server from accepting new connections. See [net.Server.close()][].
Oct 28, 2010
Oct 28, 2010
185
186
Jan 15, 2012
Jan 15, 2012
187
### server.maxHeadersCount
188
189
Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
190
no limit will be applied.
191
Mar 6, 2013
Mar 6, 2013
192
### server.setTimeout(msecs, callback)
Jan 15, 2012
Jan 15, 2012
193
Mar 6, 2013
Mar 6, 2013
194
* `msecs` {Number}
195
* `callback` {Function}
196
197
Sets the timeout value for sockets, and emits a `'timeout'` event on
198
the Server object, passing the socket as an argument, if a timeout
199
occurs.
200
201
If there is a `'timeout'` event listener on the Server object, then it
202
will be called with the timed-out socket as an argument.
203
204
By default, the Server's timeout value is 2 minutes, and sockets are
205
destroyed automatically if they time out. However, if you assign a
206
callback to the Server's `'timeout'` event, then you are responsible
207
for handling socket timeouts.
208
209
### server.timeout
210
211
* {Number} Default = 120000 (2 minutes)
212
213
The number of milliseconds of inactivity before a socket is presumed
214
to have timed out.
215
216
Note that the socket timeout logic is set up on connection, so
217
changing this value only affects *new* connections to the server, not
218
any existing connections.
219
220
Set to 0 to disable any kind of automatic timeout behavior on incoming
221
connections.
Oct 28, 2010
Oct 28, 2010
222
Feb 27, 2012
Feb 27, 2012
223
## Class: http.ServerResponse
Oct 28, 2010
Oct 28, 2010
224
225
This object is created internally by a HTTP server--not by the user. It is
Feb 5, 2012
Feb 5, 2012
226
passed as the second parameter to the `'request'` event.
227
Jun 15, 2012
Jun 15, 2012
228
The response implements the [Writable Stream][] interface. This is an
229
[EventEmitter][] with the following events:
Oct 28, 2010
Oct 28, 2010
230
Jan 6, 2012
Jan 6, 2012
231
### Event: 'close'
232
233
`function () { }`
234
Mar 28, 2013
Mar 28, 2013
235
Indicates that the underlying connection was terminated before
Jan 6, 2012
Jan 6, 2012
236
`response.end()` was called or able to flush.
237
Oct 28, 2010
Oct 28, 2010
238
### response.writeContinue()
239
240
Sends a HTTP/1.1 100 Continue message to the client, indicating that
Jun 15, 2012
Jun 15, 2012
241
the request body should be sent. See the ['checkContinue'][] event on `Server`.
Oct 28, 2010
Oct 28, 2010
242
243
### response.writeHead(statusCode, [reasonPhrase], [headers])
244
245
Sends a response header to the request. The status code is a 3-digit HTTP
246
status code, like `404`. The last argument, `headers`, are the response headers.
247
Optionally one can give a human-readable `reasonPhrase` as the second
248
argument.
249
250
Example:
251
252
var body = 'hello world';
253
response.writeHead(200, {
254
'Content-Length': body.length,
Nov 18, 2010
Nov 18, 2010
255
'Content-Type': 'text/plain' });
Oct 28, 2010
Oct 28, 2010
256
257
This method must only be called once on a message and it must
258
be called before `response.end()` is called.
259
Feb 10, 2011
Feb 10, 2011
260
If you call `response.write()` or `response.end()` before calling this, the
261
implicit/mutable headers will be calculated and call this function for you.
262
Apr 14, 2011
Apr 14, 2011
263
Note: that Content-Length is given in bytes not characters. The above example
264
works because the string `'hello world'` contains only single byte characters.
265
If the body contains higher coded characters then `Buffer.byteLength()`
266
should be used to determine the number of bytes in a given encoding.
Jul 29, 2011
Jul 29, 2011
267
And Node does not check whether Content-Length and the length of the body
268
which has been transmitted are equal or not.
Apr 14, 2011
Apr 14, 2011
269
Mar 6, 2013
Mar 6, 2013
270
### response.setTimeout(msecs, callback)
271
272
* `msecs` {Number}
273
* `callback` {Function}
274
275
Sets the Socket's timeout value to `msecs`. If a callback is
276
provided, then it is added as a listener on the `'timeout'` event on
277
the response object.
278
279
If no `'timeout'` listener is added to the request, the response, or
280
the server, then sockets are destroyed when they time out. If you
281
assign a handler on the request, the response, or the server's
282
`'timeout'` events, then it is your responsibility to handle timed out
283
sockets.
284
Feb 10, 2011
Feb 10, 2011
285
### response.statusCode
286
287
When using implicit headers (not calling `response.writeHead()` explicitly), this property
Aug 29, 2012
Aug 29, 2012
288
controls the status code that will be sent to the client when the headers get
Feb 10, 2011
Feb 10, 2011
289
flushed.
290
291
Example:
292
293
response.statusCode = 404;
294
Jul 21, 2011
Jul 21, 2011
295
After response header was sent to the client, this property indicates the
296
status code which was sent out.
297
Feb 10, 2011
Feb 10, 2011
298
### response.setHeader(name, value)
299
300
Sets a single header value for implicit headers. If this header already exists
Sep 6, 2011
Sep 6, 2011
301
in the to-be-sent headers, its value will be replaced. Use an array of strings
Feb 10, 2011
Feb 10, 2011
302
here if you need to send multiple headers with the same name.
303
304
Example:
305
306
response.setHeader("Content-Type", "text/html");
307
308
or
309
310
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
311
Sep 28, 2012
Sep 28, 2012
312
### response.headersSent
313
314
Boolean (read-only). True if headers were sent, false otherwise.
315
Feb 15, 2012
Feb 15, 2012
316
### response.sendDate
317
Jul 30, 2013
Jul 30, 2013
318
When true, the Date header will be automatically generated and sent in
Feb 15, 2012
Feb 15, 2012
319
the response if it is not already present in the headers. Defaults to true.
320
321
This should only be disabled for testing; HTTP requires the Date header
322
in responses.
Feb 10, 2011
Feb 10, 2011
323
324
### response.getHeader(name)
325
326
Reads out a header that's already been queued but not sent to the client. Note
327
that the name is case insensitive. This can only be called before headers get
328
implicitly flushed.
329
330
Example:
331
332
var contentType = response.getHeader('content-type');
333
334
### response.removeHeader(name)
335
336
Removes a header that's queued for implicit sending.
337
338
Example:
339
340
response.removeHeader("Content-Encoding");
341
342
Dec 27, 2011
Dec 27, 2011
343
### response.write(chunk, [encoding])
Oct 28, 2010
Oct 28, 2010
344
Feb 10, 2011
Feb 10, 2011
345
If this method is called and `response.writeHead()` has not been called, it will
346
switch to implicit header mode and flush the implicit headers.
347
348
This sends a chunk of the response body. This method may
Oct 28, 2010
Oct 28, 2010
349
be called multiple times to provide successive parts of the body.
350
351
`chunk` can be a string or a buffer. If `chunk` is a string,
352
the second parameter specifies how to encode it into a byte stream.
353
By default the `encoding` is `'utf8'`.
354
355
**Note**: This is the raw HTTP body and has nothing to do with
356
higher-level multi-part body encodings that may be used.
357
358
The first time `response.write()` is called, it will send the buffered
359
header information and the first body to the client. The second time
360
`response.write()` is called, Node assumes you're going to be streaming
361
data, and sends that separately. That is, the response is buffered up to the
362
first chunk of body.
363
Jul 31, 2012
Jul 31, 2012
364
Returns `true` if the entire data was flushed successfully to the kernel
365
buffer. Returns `false` if all or part of the data was queued in user memory.
366
`'drain'` will be emitted when the buffer is again free.
367
Oct 28, 2010
Oct 28, 2010
368
### response.addTrailers(headers)
369
370
This method adds HTTP trailing headers (a header but at the end of the
Nov 21, 2010
Nov 21, 2010
371
message) to the response.
Oct 28, 2010
Oct 28, 2010
372
Nov 21, 2010
Nov 21, 2010
373
Trailers will **only** be emitted if chunked encoding is used for the
Oct 28, 2010
Oct 28, 2010
374
response; if it is not (e.g., if the request was HTTP/1.0), they will
375
be silently discarded.
376
377
Note that HTTP requires the `Trailer` header to be sent if you intend to
378
emit trailers, with a list of the header fields in its value. E.g.,
379
380
response.writeHead(200, { 'Content-Type': 'text/plain',
Nov 15, 2011
Nov 15, 2011
381
'Trailer': 'Content-MD5' });
Oct 28, 2010
Oct 28, 2010
382
response.write(fileData);
383
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
384
response.end();
385
386
387
### response.end([data], [encoding])
388
389
This method signals to the server that all of the response headers and body
Aug 29, 2012
Aug 29, 2012
390
have been sent; that server should consider this message complete.
Oct 28, 2010
Oct 28, 2010
391
The method, `response.end()`, MUST be called on each
392
response.
393
394
If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
395
followed by `response.end()`.
396
397
Jan 21, 2011
Jan 21, 2011
398
## http.request(options, callback)
Oct 28, 2010
Oct 28, 2010
399
Jan 21, 2011
Jan 21, 2011
400
Node maintains several connections per server to make HTTP requests.
May 16, 2012
May 16, 2012
401
This function allows one to transparently issue requests.
402
403
`options` can be an object or a string. If `options` is a string, it is
Jun 15, 2012
Jun 15, 2012
404
automatically parsed with [url.parse()][].
Oct 28, 2010
Oct 28, 2010
405
Jan 21, 2011
Jan 21, 2011
406
Options:
Oct 28, 2010
Oct 28, 2010
407
Jan 21, 2011
Jan 21, 2011
408
- `host`: A domain name or IP address of the server to issue the request to.
Oct 22, 2011
Oct 22, 2011
409
Defaults to `'localhost'`.
Nov 26, 2011
Nov 26, 2011
410
- `hostname`: To support `url.parse()` `hostname` is preferred over `host`
Oct 22, 2011
Oct 22, 2011
411
- `port`: Port of remote server. Defaults to 80.
Mar 6, 2012
Mar 6, 2012
412
- `localAddress`: Local interface to bind for network connections.
Apr 25, 2011
Apr 25, 2011
413
- `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
Oct 22, 2011
Oct 22, 2011
414
- `method`: A string specifying the HTTP request method. Defaults to `'GET'`.
415
- `path`: Request path. Defaults to `'/'`. Should include query string if any.
May 15, 2013
May 15, 2013
416
E.G. `'/index.html?page=12'`. An exception is thrown when the request path
417
contains illegal characters. Currently, only spaces are rejected but that
418
may change in the future.
Jan 21, 2011
Jan 21, 2011
419
- `headers`: An object containing request headers.
Oct 22, 2011
Oct 22, 2011
420
- `auth`: Basic authentication i.e. `'user:password'` to compute an
421
Authorization header.
Jun 15, 2012
Jun 15, 2012
422
- `agent`: Controls [Agent][] behavior. When an Agent is used request will
423
default to `Connection: keep-alive`. Possible values:
424
- `undefined` (default): use [global Agent][] for this host and port.
Jul 13, 2011
Jul 13, 2011
425
- `Agent` object: explicitly use the passed in `Agent`.
Oct 22, 2011
Oct 22, 2011
426
- `false`: opts out of connection pooling with an Agent, defaults request to
427
`Connection: close`.
Aug 15, 2013
Aug 15, 2013
428
- `keepAlive`: {Boolean} Keep sockets around in a pool to be used
429
by other requests in the future. Default = `false`
430
- `keepAliveMsecs`: {Integer} When using HTTP KeepAlive, how often to
431
send TCP KeepAlive packets over sockets being kept alive. Default =
432
`1000`. Only relevant if `keepAlive` is set to `true`.
Jan 21, 2011
Jan 21, 2011
433
434
`http.request()` returns an instance of the `http.ClientRequest`
435
class. The `ClientRequest` instance is a writable stream. If one needs to
436
upload a file with a POST request, then write to the `ClientRequest` object.
437
438
Example:
439
440
var options = {
Oct 29, 2012
Oct 29, 2012
441
hostname: 'www.google.com',
Jan 21, 2011
Jan 21, 2011
442
port: 80,
443
path: '/upload',
444
method: 'POST'
445
};
446
447
var req = http.request(options, function(res) {
448
console.log('STATUS: ' + res.statusCode);
449
console.log('HEADERS: ' + JSON.stringify(res.headers));
450
res.setEncoding('utf8');
451
res.on('data', function (chunk) {
Oct 28, 2010
Oct 28, 2010
452
console.log('BODY: ' + chunk);
453
});
454
});
455
May 5, 2011
May 5, 2011
456
req.on('error', function(e) {
457
console.log('problem with request: ' + e.message);
458
});
459
Jan 21, 2011
Jan 21, 2011
460
// write data to request body
461
req.write('data\n');
462
req.write('data\n');
463
req.end();
464
465
Note that in the example `req.end()` was called. With `http.request()` one
466
must always call `req.end()` to signify that you're done with the request -
467
even if there is no data being written to the request body.
Oct 28, 2010
Oct 28, 2010
468
Jan 21, 2011
Jan 21, 2011
469
If any error is encountered during the request (be that with DNS resolution,
470
TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
471
on the returned request object.
472
473
There are a few special headers that should be noted.
Oct 28, 2010
Oct 28, 2010
474
475
* Sending a 'Connection: keep-alive' will notify Node that the connection to
476
the server should be persisted until the next request.
477
478
* Sending a 'Content-length' header will disable the default chunked encoding.
479
Nov 21, 2010
Nov 21, 2010
480
* Sending an 'Expect' header will immediately send the request headers.
Oct 28, 2010
Oct 28, 2010
481
Usually, when sending 'Expect: 100-continue', you should both set a timeout
482
and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
483
information.
484
Nov 26, 2011
Nov 26, 2011
485
* Sending an Authorization header will override using the `auth` option
Oct 22, 2011
Oct 22, 2011
486
to compute basic authentication.
487
Jan 21, 2011
Jan 21, 2011
488
## http.get(options, callback)
489
490
Since most requests are GET requests without bodies, Node provides this
May 16, 2012
May 16, 2012
491
convenience method. The only difference between this method and `http.request()`
492
is that it sets the method to GET and calls `req.end()` automatically.
Jan 21, 2011
Jan 21, 2011
493
494
Example:
495
May 16, 2012
May 16, 2012
496
http.get("http://www.google.com/index.html", function(res) {
Jan 21, 2011
Jan 21, 2011
497
console.log("Got response: " + res.statusCode);
498
}).on('error', function(e) {
499
console.log("Got error: " + e.message);
500
});
501
502
Feb 27, 2012
Feb 27, 2012
503
## Class: http.Agent
Jan 21, 2011
Jan 21, 2011
504
Aug 15, 2013
Aug 15, 2013
505
The HTTP Agent is used for pooling sockets used in HTTP client
506
requests.
Aug 24, 2011
Aug 24, 2011
507
Aug 15, 2013
Aug 15, 2013
508
The HTTP Agent also defaults client requests to using
509
Connection:keep-alive. If no pending HTTP requests are waiting on a
510
socket to become free the socket is closed. This means that Node's
511
pool has the benefit of keep-alive when under load but still does not
512
require developers to manually close the HTTP clients using
513
KeepAlive.
514
515
If you opt into using HTTP KeepAlive, you can create an Agent object
516
with that flag set to `true`. (See the [constructor
517
options](#http_new_agent_options) below.) Then, the Agent will keep
518
unused sockets in a pool for later use. They will be explicitly
519
marked so as to not keep the Node process running. However, it is
520
still a good idea to explicitly [`destroy()`](#http_agent_destroy)
521
KeepAlive agents when they are no longer in use, so that the Sockets
522
will be shut down.
523
524
Sockets are removed from the agent's pool when the socket emits either
525
a "close" event or a special "agentRemove" event. This means that if
526
you intend to keep one HTTP request open for a long time and don't
527
want it to stay in the pool you can do something along the lines of:
Aug 24, 2011
Aug 24, 2011
528
529
http.get(options, function(res) {
530
// Do stuff
531
}).on("socket", function (socket) {
532
socket.emit("agentRemove");
533
});
Oct 22, 2011
Oct 22, 2011
534
Aug 15, 2013
Aug 15, 2013
535
Alternatively, you could just opt out of pooling entirely using
536
`agent:false`:
Aug 24, 2011
Aug 24, 2011
537
Aug 15, 2013
Aug 15, 2013
538
http.get({
539
hostname: 'localhost',
540
port: 80,
541
path: '/',
542
agent: false // create a new agent just for this one request
543
}, function (res) {
544
// Do stuff with response
Aug 24, 2011
Aug 24, 2011
545
})
546
Aug 15, 2013
Aug 15, 2013
547
### new Agent([options])
548
549
* `options` {Object} Set of configurable options to set on the agent.
550
Can have the following fields:
551
* `keepAlive` {Boolean} Keep sockets around in a pool to be used by
552
other requests in the future. Default = `false`
553
* `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often
554
to send TCP KeepAlive packets over sockets being kept alive.
555
Default = `1000`. Only relevant if `keepAlive` is set to `true`.
556
* `maxSockets` {Number} Maximum number of sockets to allow per
557
host. Default = `Infinity`.
558
* `maxFreeSockets` {Number} Maximum number of sockets to leave open
559
in a free state. Only relevant if `keepAlive` is set to `true`.
560
Default = `256`.
561
562
The default `http.globalAgent` that is used by `http.request` has all
563
of these values set to their respective defaults.
564
565
To configure any of them, you must create your own `Agent` object.
566
567
```javascript
568
var http = require('http');
569
var keepAliveAgent = new http.Agent({ keepAlive: true });
570
keepAliveAgent.request(options, onResponseCallback);
571
```
572
Jul 26, 2011
Jul 26, 2011
573
### agent.maxSockets
574
Aug 15, 2013
Aug 15, 2013
575
By default set to Infinity. Determines how many concurrent sockets the
576
agent can have open per host.
577
578
### agent.maxFreeSockets
579
580
By default set to 256. For Agents supporting HTTP KeepAlive, this
581
sets the maximum number of sockets that will be left open in the free
582
state.
Jul 26, 2011
Jul 26, 2011
583
584
### agent.sockets
585
Aug 15, 2013
Aug 15, 2013
586
An object which contains arrays of sockets currently in use by the
587
Agent. Do not modify.
588
589
### agent.freeSockets
590
591
An object which contains arrays of sockets currently awaiting use by
592
the Agent when HTTP KeepAlive is used. Do not modify.
Jul 26, 2011
Jul 26, 2011
593
594
### agent.requests
595
Jul 30, 2013
Jul 30, 2013
596
An object which contains queues of requests that have not yet been assigned to
Aug 24, 2011
Aug 24, 2011
597
sockets. Do not modify.
Jul 26, 2011
Jul 26, 2011
598
Aug 15, 2013
Aug 15, 2013
599
### agent.destroy()
600
601
Destroy any sockets that are currently in use by the agent.
602
603
It is usually not necessary to do this. However, if you are using an
604
agent with KeepAlive enabled, then it is best to explicitly shut down
605
the agent when you know that it will no longer be used. Otherwise,
606
sockets may hang open for quite a long time before the server
607
terminates them.
608
609
### agent.getName(options)
610
611
Get a unique name for a set of request options, to determine whether a
612
connection can be reused. In the http agent, this returns
613
`host:port:localAddress`. In the https agent, the name includes the
614
CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
615
socket reusability.
616
617
Feb 27, 2012
Feb 27, 2012
618
## http.globalAgent
619
620
Global instance of Agent which is used as the default for all http client
621
requests.
622
Jul 26, 2011
Jul 26, 2011
623
Feb 27, 2012
Feb 27, 2012
624
## Class: http.ClientRequest
Jul 26, 2011
Jul 26, 2011
625
626
This object is created internally and returned from `http.request()`. It
627
represents an _in-progress_ request whose header has already been queued. The
628
header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
629
`removeHeader(name)` API. The actual header will be sent along with the first
630
data chunk or when closing the connection.
631
632
To get the response, add a listener for `'response'` to the request object.
633
`'response'` will be emitted from the request object when the response
634
headers have been received. The `'response'` event is executed with one
Feb 7, 2013
Feb 7, 2013
635
argument which is an instance of `http.IncomingMessage`.
Jul 26, 2011
Jul 26, 2011
636
637
During the `'response'` event, one can add listeners to the
Apr 5, 2013
Apr 5, 2013
638
response object; particularly to listen for the `'data'` event.
Jul 26, 2011
Jul 26, 2011
639
Apr 5, 2013
Apr 5, 2013
640
If no `'response'` handler is added, then the response will be
641
entirely discarded. However, if you add a `'response'` event handler,
642
then you **must** consume the data from the response object, either by
643
calling `response.read()` whenever there is a `'readable'` event, or
644
by adding a `'data'` handler, or by calling the `.resume()` method.
Jul 30, 2013
Jul 30, 2013
645
Until the data is consumed, the `'end'` event will not fire. Also, until
646
the data is read it will consume memory that can eventually lead to a
647
'process out of memory' error.
Jul 26, 2011
Jul 26, 2011
648
Jul 29, 2011
Jul 29, 2011
649
Note: Node does not check whether Content-Length and the length of the body
650
which has been transmitted are equal or not.
Jul 26, 2011
Jul 26, 2011
651
Jun 15, 2012
Jun 15, 2012
652
The request implements the [Writable Stream][] interface. This is an
653
[EventEmitter][] with the following events:
Jul 26, 2011
Jul 26, 2011
654
655
### Event 'response'
656
657
`function (response) { }`
658
Jun 15, 2012
Jun 15, 2012
659
Emitted when a response is received to this request. This event is emitted only
Feb 7, 2013
Feb 7, 2013
660
once. The `response` argument will be an instance of `http.IncomingMessage`.
Oct 28, 2010
Oct 28, 2010
661
Apr 25, 2011
Apr 25, 2011
662
Options:
663
664
- `host`: A domain name or IP address of the server to issue the request to.
665
- `port`: Port of remote server.
666
- `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
667
Jul 26, 2011
Jul 26, 2011
668
### Event: 'socket'
669
670
`function (socket) { }`
671
672
Emitted after a socket is assigned to this request.
673
Jan 9, 2012
Jan 9, 2012
674
### Event: 'connect'
675
Jun 13, 2013
Jun 13, 2013
676
`function (response, socket, head) { }`
Jan 9, 2012
Jan 9, 2012
677
678
Emitted each time a server responds to a request with a CONNECT method. If this
679
event isn't being listened for, clients receiving a CONNECT method will have
680
their connections closed.
681
682
A client server pair that show you how to listen for the `connect` event.
683
684
var http = require('http');
685
var net = require('net');
686
var url = require('url');
687
688
// Create an HTTP tunneling proxy
689
var proxy = http.createServer(function (req, res) {
690
res.writeHead(200, {'Content-Type': 'text/plain'});
691
res.end('okay');
692
});
Jun 13, 2013
Jun 13, 2013
693
proxy.on('connect', function(req, cltSocket, head) {
Jan 9, 2012
Jan 9, 2012
694
// connect to an origin server
695
var srvUrl = url.parse('http://' + req.url);
696
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
697
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
698
'Proxy-agent: Node-Proxy\r\n' +
699
'\r\n');
Jun 13, 2013
Jun 13, 2013
700
srvSocket.write(head);
Jan 9, 2012
Jan 9, 2012
701
srvSocket.pipe(cltSocket);
702
cltSocket.pipe(srvSocket);
703
});
704
});
705
706
// now that proxy is running
707
proxy.listen(1337, '127.0.0.1', function() {
708
709
// make a request to a tunneling proxy
710
var options = {
711
port: 1337,
Oct 29, 2012
Oct 29, 2012
712
hostname: '127.0.0.1',
Jan 9, 2012
Jan 9, 2012
713
method: 'CONNECT',
714
path: 'www.google.com:80'
715
};
716
717
var req = http.request(options);
718
req.end();
719
Jun 13, 2013
Jun 13, 2013
720
req.on('connect', function(res, socket, head) {
Jan 9, 2012
Jan 9, 2012
721
console.log('got connected!');
722
723
// make a request over an HTTP tunnel
724
socket.write('GET / HTTP/1.1\r\n' +
725
'Host: www.google.com:80\r\n' +
726
'Connection: close\r\n' +
727
'\r\n');
728
socket.on('data', function(chunk) {
729
console.log(chunk.toString());
730
});
731
socket.on('end', function() {
732
proxy.close();
733
});
734
});
735
});
736
Oct 28, 2010
Oct 28, 2010
737
### Event: 'upgrade'
738
Jun 13, 2013
Jun 13, 2013
739
`function (response, socket, head) { }`
May 20, 2011
May 20, 2011
740
741
Emitted each time a server responds to a request with an upgrade. If this
742
event isn't being listened for, clients receiving an upgrade header will have
743
their connections closed.
744
Jan 9, 2012
Jan 9, 2012
745
A client server pair that show you how to listen for the `upgrade` event.
Oct 28, 2010
Oct 28, 2010
746
May 20, 2011
May 20, 2011
747
var http = require('http');
748
749
// Create an HTTP server
750
var srv = http.createServer(function (req, res) {
751
res.writeHead(200, {'Content-Type': 'text/plain'});
752
res.end('okay');
753
});
Jun 13, 2013
Jun 13, 2013
754
srv.on('upgrade', function(req, socket, head) {
May 20, 2011
May 20, 2011
755
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
756
'Upgrade: WebSocket\r\n' +
757
'Connection: Upgrade\r\n' +
Jan 9, 2012
Jan 9, 2012
758
'\r\n');
May 20, 2011
May 20, 2011
759
Jan 9, 2012
Jan 9, 2012
760
socket.pipe(socket); // echo back
May 20, 2011
May 20, 2011
761
});
762
763
// now that server is running
764
srv.listen(1337, '127.0.0.1', function() {
765
766
// make a request
767
var options = {
768
port: 1337,
Oct 29, 2012
Oct 29, 2012
769
hostname: '127.0.0.1',
May 20, 2011
May 20, 2011
770
headers: {
771
'Connection': 'Upgrade',
772
'Upgrade': 'websocket'
773
}
774
};
775
776
var req = http.request(options);
777
req.end();
778
Jun 13, 2013
Jun 13, 2013
779
req.on('upgrade', function(res, socket, upgradeHead) {
May 20, 2011
May 20, 2011
780
console.log('got upgraded!');
781
socket.end();
782
process.exit(0);
783
});
784
});
Oct 28, 2010
Oct 28, 2010
785
Jul 9, 2011
Jul 9, 2011
786
### Event: 'continue'
787
Dec 29, 2011
Dec 29, 2011
788
`function () { }`
Jul 9, 2011
Jul 9, 2011
789
790
Emitted when the server sends a '100 Continue' HTTP response, usually because
791
the request contained 'Expect: 100-continue'. This is an instruction that
792
the client should send the request body.
793
Dec 27, 2011
Dec 27, 2011
794
### request.write(chunk, [encoding])
Oct 28, 2010
Oct 28, 2010
795
796
Sends a chunk of the body. By calling this method
797
many times, the user can stream a request body to a
798
server--in that case it is suggested to use the
799
`['Transfer-Encoding', 'chunked']` header line when
800
creating the request.
801
Jun 15, 2012
Jun 15, 2012
802
The `chunk` argument should be a [Buffer][] or a string.
Oct 28, 2010
Oct 28, 2010
803
Dec 27, 2011
Dec 27, 2011
804
The `encoding` argument is optional and only applies when `chunk` is a string.
805
Defaults to `'utf8'`.
Oct 28, 2010
Oct 28, 2010
806
807
808
### request.end([data], [encoding])
809
810
Finishes sending the request. If any parts of the body are
811
unsent, it will flush them to the stream. If the request is
812
chunked, this will send the terminating `'0\r\n\r\n'`.
813
Dec 27, 2011
Dec 27, 2011
814
If `data` is specified, it is equivalent to calling
815
`request.write(data, encoding)` followed by `request.end()`.
Oct 28, 2010
Oct 28, 2010
816
Feb 5, 2011
Feb 5, 2011
817
### request.abort()
818
Feb 5, 2011
Feb 5, 2011
819
Aborts a request. (New since v0.3.8.)
Feb 5, 2011
Feb 5, 2011
820
Aug 24, 2011
Aug 24, 2011
821
### request.setTimeout(timeout, [callback])
822
Jun 15, 2012
Jun 15, 2012
823
Once a socket is assigned to this request and is connected
824
[socket.setTimeout()][] will be called.
Aug 24, 2011
Aug 24, 2011
825
Dec 27, 2011
Dec 27, 2011
826
### request.setNoDelay([noDelay])
Aug 24, 2011
Aug 24, 2011
827
Jun 15, 2012
Jun 15, 2012
828
Once a socket is assigned to this request and is connected
829
[socket.setNoDelay()][] will be called.
Aug 24, 2011
Aug 24, 2011
830
Dec 27, 2011
Dec 27, 2011
831
### request.setSocketKeepAlive([enable], [initialDelay])
Aug 24, 2011
Aug 24, 2011
832
Jun 15, 2012
Jun 15, 2012
833
Once a socket is assigned to this request and is connected
834
[socket.setKeepAlive()][] will be called.
Oct 28, 2010
Oct 28, 2010
835
836
Feb 7, 2013
Feb 7, 2013
837
## http.IncomingMessage
Oct 28, 2010
Oct 28, 2010
838
Feb 7, 2013
Feb 7, 2013
839
An `IncomingMessage` object is created by `http.Server` or `http.ClientRequest`
840
and passed as the first argument to the `'request'` and `'response'` event
841
respectively. It may be used to access response status, headers and data.
Feb 5, 2012
Feb 5, 2012
842
Apr 5, 2013
Apr 5, 2013
843
It implements the [Readable Stream][] interface, as well as the
844
following additional events, methods, and properties.
Oct 13, 2012
Oct 13, 2012
845
Jul 9, 2011
Jul 9, 2011
846
### Event: 'close'
847
Oct 13, 2012
Oct 13, 2012
848
`function () { }`
Jul 9, 2011
Jul 9, 2011
849
850
Indicates that the underlaying connection was terminated before
Oct 13, 2012
Oct 13, 2012
851
`response.end()` was called or able to flush.
852
Apr 5, 2013
Apr 5, 2013
853
Just like `'end'`, this event occurs only once per response. See
854
[http.ServerResponse][]'s `'close'` event for more information.
Oct 13, 2012
Oct 13, 2012
855
Feb 7, 2013
Feb 7, 2013
856
### message.httpVersion
Jul 9, 2011
Jul 9, 2011
857
Feb 7, 2013
Feb 7, 2013
858
In case of server request, the HTTP version sent by the client. In the case of
859
client response, the HTTP version of the connected-to server.
860
Probably either `'1.1'` or `'1.0'`.
Oct 28, 2010
Oct 28, 2010
861
862
Also `response.httpVersionMajor` is the first integer and
863
`response.httpVersionMinor` is the second.
864
Feb 7, 2013
Feb 7, 2013
865
### message.headers
Oct 28, 2010
Oct 28, 2010
866
Feb 7, 2013
Feb 7, 2013
867
The request/response headers object.
Oct 28, 2010
Oct 28, 2010
868
Feb 7, 2013
Feb 7, 2013
869
Read only map of header names and values. Header names are lower-cased.
870
Example:
Oct 28, 2010
Oct 28, 2010
871
Feb 7, 2013
Feb 7, 2013
872
// Prints something like:
873
//
874
// { 'user-agent': 'curl/7.22.0',
875
// host: '127.0.0.1:8000',
876
// accept: '*/*' }
877
console.log(request.headers);
Oct 28, 2010
Oct 28, 2010
878
Feb 7, 2013
Feb 7, 2013
879
### message.trailers
Oct 28, 2010
Oct 28, 2010
880
Feb 7, 2013
Feb 7, 2013
881
The request/response trailers object. Only populated after the 'end' event.
882
Mar 6, 2013
Mar 6, 2013
883
### message.setTimeout(msecs, callback)
884
885
* `msecs` {Number}
886
* `callback` {Function}
887
888
Calls `message.connection.setTimeout(msecs, callback)`.
889
Feb 7, 2013
Feb 7, 2013
890
### message.method
891
892
**Only valid for request obtained from `http.Server`.**
893
894
The request method as a string. Read only. Example:
895
`'GET'`, `'DELETE'`.
896
897
### message.url
898
899
**Only valid for request obtained from `http.Server`.**
900
901
Request URL string. This contains only the URL that is
902
present in the actual HTTP request. If the request is:
903
904
GET /status?name=ryan HTTP/1.1\r\n
905
Accept: text/plain\r\n
906
\r\n
907
908
Then `request.url` will be:
909
910
'/status?name=ryan'
911
912
If you would like to parse the URL into its parts, you can use
913
`require('url').parse(request.url)`. Example:
914
915
node> require('url').parse('/status?name=ryan')
916
{ href: '/status?name=ryan',
917
search: '?name=ryan',
918
query: 'name=ryan',
919
pathname: '/status' }
920
921
If you would like to extract the params from the query string,
922
you can use the `require('querystring').parse` function, or pass
923
`true` as the second argument to `require('url').parse`. Example:
Oct 28, 2010
Oct 28, 2010
924
Feb 7, 2013
Feb 7, 2013
925
node> require('url').parse('/status?name=ryan', true)
926
{ href: '/status?name=ryan',
927
search: '?name=ryan',
928
query: { name: 'ryan' },
929
pathname: '/status' }
Oct 28, 2010
Oct 28, 2010
930
Feb 7, 2013
Feb 7, 2013
931
### message.statusCode
932
933
**Only valid for response obtained from `http.ClientRequest`.**
934
935
The 3-digit HTTP response status code. E.G. `404`.
936
937
### message.socket
938
939
The `net.Socket` object associated with the connection.
940
941
With HTTPS support, use request.connection.verifyPeer() and
942
request.connection.getPeerCertificate() to obtain the client's
943
authentication details.
Oct 28, 2010
Oct 28, 2010
944
Jun 15, 2012
Jun 15, 2012
945
946
[Agent]: #http_class_http_agent
947
['checkContinue']: #http_event_checkcontinue
948
[Buffer]: buffer.html#buffer_buffer
949
[EventEmitter]: events.html#events_class_events_eventemitter
950
[global Agent]: #http_http_globalagent
951
[http.request()]: #http_http_request_options_callback
Feb 7, 2013
Feb 7, 2013
952
[http.IncomingMessage]: #http_class_http_incomingmessage
Jun 15, 2012
Jun 15, 2012
953
['listening']: net.html#net_event_listening
Oct 8, 2012
Oct 8, 2012
954
[net.Server.close()]: net.html#net_server_close_callback
955
[net.Server.listen(path)]: net.html#net_server_listen_path_callback
956
[net.Server.listen(port)]: net.html#net_server_listen_port_host_backlog_callback
Jun 15, 2012
Jun 15, 2012
957
[Readable Stream]: stream.html#stream_readable_stream
958
[socket.setKeepAlive()]: net.html#net_socket_setkeepalive_enable_initialdelay
959
[socket.setNoDelay()]: net.html#net_socket_setnodelay_nodelay
960
[socket.setTimeout()]: net.html#net_socket_settimeout_timeout_callback
961
[stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding
962
[url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
963
[Writable Stream]: stream.html#stream_writable_stream