Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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