Merge branch 'http_agent'
[platform/upstream/nodejs.git] / doc / api / http.markdown
1 ## HTTP
2
3 To use the HTTP server and client one must `require('http')`.
4
5 The HTTP interfaces in Node are designed to support many features
6 of the protocol which have been traditionally difficult to use.
7 In particular, large, possibly chunk-encoded, messages. The interface is
8 careful to never buffer entire requests or responses--the
9 user is able to stream data.
10
11 HTTP message headers are represented by an object like this:
12
13     { 'content-length': '123',
14       'content-type': 'text/plain',
15       'connection': 'keep-alive',
16       'accept': '*/*' }
17
18 Keys are lowercased. Values are not modified.
19
20 In order to support the full spectrum of possible HTTP applications, Node's
21 HTTP API is very low-level. It deals with stream handling and message
22 parsing only. It parses a message into headers and body but it does not
23 parse the actual headers or the body.
24
25
26 ## http.Server
27
28 This is an `EventEmitter` with the following events:
29
30 ### Event: 'request'
31
32 `function (request, response) { }`
33
34  `request` is an instance of `http.ServerRequest` and `response` is
35  an instance of `http.ServerResponse`
36
37 ### Event: 'connection'
38
39 `function (stream) { }`
40
41  When a new TCP stream is established. `stream` is an object of type
42  `net.Stream`. Usually users will not want to access this event. The
43  `stream` can also be accessed at `request.connection`.
44
45 ### Event: 'close'
46
47 `function (errno) { }`
48
49  Emitted when the server closes.
50
51 ### Event: 'request'
52
53 `function (request, response) {}`
54
55 Emitted each time there is request. Note that there may be multiple requests
56 per connection (in the case of keep-alive connections).
57
58 ### Event: 'checkContinue'
59
60 `function (request, response) {}`
61
62 Emitted each time a request with an http Expect: 100-continue is received.
63 If this event isn't listened for, the server will automatically respond
64 with a 100 Continue as appropriate.
65
66 Handling this event involves calling `response.writeContinue` if the client
67 should continue to send the request body, or generating an appropriate HTTP
68 response (e.g., 400 Bad Request) if the client should not continue to send the
69 request body.
70
71 Note that when this event is emitted and handled, the `request` event will
72 not be emitted.
73
74 ### Event: 'upgrade'
75
76 `function (request, socket, head)`
77
78 Emitted each time a client requests a http upgrade. If this event isn't
79 listened for, then clients requesting an upgrade will have their connections
80 closed.
81
82 * `request` is the arguments for the http request, as it is in the request event.
83 * `socket` is the network socket between the server and client.
84 * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
85
86 After this event is emitted, the request's socket will not have a `data`
87 event listener, meaning you will need to bind to it in order to handle data
88 sent to the server on that socket.
89
90 ### Event: 'clientError'
91
92 `function (exception) {}`
93
94 If a client connection emits an 'error' event - it will forwarded here.
95
96 ### http.createServer(requestListener)
97
98 Returns a new web server object.
99
100 The `requestListener` is a function which is automatically
101 added to the `'request'` event.
102
103 ### server.listen(port, [hostname], [callback])
104
105 Begin accepting connections on the specified port and hostname.  If the
106 hostname is omitted, the server will accept connections directed to any
107 IPv4 address (`INADDR_ANY`).
108
109 To listen to a unix socket, supply a filename instead of port and hostname.
110
111 This function is asynchronous. The last parameter `callback` will be called
112 when the server has been bound to the port.
113
114
115 ### server.listen(path, [callback])
116
117 Start a UNIX socket server listening for connections on the given `path`.
118
119 This function is asynchronous. The last parameter `callback` will be called
120 when the server has been bound.
121
122
123 ### server.close()
124
125 Stops the server from accepting new connections.
126
127
128 ## http.ServerRequest
129
130 This object is created internally by a HTTP server -- not by
131 the user -- and passed as the first argument to a `'request'` listener.
132
133 This is an `EventEmitter` with the following events:
134
135 ### Event: 'data'
136
137 `function (chunk) { }`
138
139 Emitted when a piece of the message body is received.
140
141 Example: A chunk of the body is given as the single
142 argument. The transfer-encoding has been decoded.  The
143 body chunk is a string.  The body encoding is set with
144 `request.setBodyEncoding()`.
145
146 ### Event: 'end'
147
148 `function () { }`
149
150 Emitted exactly once for each message. No arguments.  After
151 emitted no other events will be emitted on the request.
152
153
154 ### request.method
155
156 The request method as a string. Read only. Example:
157 `'GET'`, `'DELETE'`.
158
159
160 ### request.url
161
162 Request URL string. This contains only the URL that is
163 present in the actual HTTP request. If the request is:
164
165     GET /status?name=ryan HTTP/1.1\r\n
166     Accept: text/plain\r\n
167     \r\n
168
169 Then `request.url` will be:
170
171     '/status?name=ryan'
172
173 If you would like to parse the URL into its parts, you can use
174 `require('url').parse(request.url)`.  Example:
175
176     node> require('url').parse('/status?name=ryan')
177     { href: '/status?name=ryan',
178       search: '?name=ryan',
179       query: 'name=ryan',
180       pathname: '/status' }
181
182 If you would like to extract the params from the query string,
183 you can use the `require('querystring').parse` function, or pass
184 `true` as the second argument to `require('url').parse`.  Example:
185
186     node> require('url').parse('/status?name=ryan', true)
187     { href: '/status?name=ryan',
188       search: '?name=ryan',
189       query: { name: 'ryan' },
190       pathname: '/status' }
191
192
193
194 ### request.headers
195
196 Read only.
197
198 ### request.trailers
199
200 Read only; HTTP trailers (if present). Only populated after the 'end' event.
201
202 ### request.httpVersion
203
204 The HTTP protocol version as a string. Read only. Examples:
205 `'1.1'`, `'1.0'`.
206 Also `request.httpVersionMajor` is the first integer and
207 `request.httpVersionMinor` is the second.
208
209
210 ### request.setEncoding(encoding=null)
211
212 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
213 to `null`, which means that the `'data'` event will emit a `Buffer` object..
214
215
216 ### request.pause()
217
218 Pauses request from emitting events.  Useful to throttle back an upload.
219
220
221 ### request.resume()
222
223 Resumes a paused request.
224
225 ### request.connection
226
227 The `net.Stream` object associated with the connection.
228
229
230 With HTTPS support, use request.connection.verifyPeer() and
231 request.connection.getPeerCertificate() to obtain the client's
232 authentication details.
233
234
235
236 ## http.ServerResponse
237
238 This object is created internally by a HTTP server--not by the user. It is
239 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
240
241 ### response.writeContinue()
242
243 Sends a HTTP/1.1 100 Continue message to the client, indicating that
244 the request body should be sent. See the the `checkContinue` event on
245 `Server`.
246
247 ### response.writeHead(statusCode, [reasonPhrase], [headers])
248
249 Sends a response header to the request. The status code is a 3-digit HTTP
250 status code, like `404`. The last argument, `headers`, are the response headers.
251 Optionally one can give a human-readable `reasonPhrase` as the second
252 argument.
253
254 Example:
255
256     var body = 'hello world';
257     response.writeHead(200, {
258       'Content-Length': body.length,
259       'Content-Type': 'text/plain' });
260
261 This method must only be called once on a message and it must
262 be called before `response.end()` is called.
263
264 ### response.write(chunk, encoding='utf8')
265
266 This method must be called after `writeHead` was
267 called. It sends a chunk of the response body. This method may
268 be called multiple times to provide successive parts of the body.
269
270 `chunk` can be a string or a buffer. If `chunk` is a string,
271 the second parameter specifies how to encode it into a byte stream.
272 By default the `encoding` is `'utf8'`.
273
274 **Note**: This is the raw HTTP body and has nothing to do with
275 higher-level multi-part body encodings that may be used.
276
277 The first time `response.write()` is called, it will send the buffered
278 header information and the first body to the client. The second time
279 `response.write()` is called, Node assumes you're going to be streaming
280 data, and sends that separately. That is, the response is buffered up to the
281 first chunk of body.
282
283 ### response.addTrailers(headers)
284
285 This method adds HTTP trailing headers (a header but at the end of the
286 message) to the response.
287
288 Trailers will **only** be emitted if chunked encoding is used for the
289 response; if it is not (e.g., if the request was HTTP/1.0), they will
290 be silently discarded.
291
292 Note that HTTP requires the `Trailer` header to be sent if you intend to
293 emit trailers, with a list of the header fields in its value. E.g.,
294
295     response.writeHead(200, { 'Content-Type': 'text/plain',
296                               'Trailer': 'TraceInfo' });
297     response.write(fileData);
298     response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
299     response.end();
300
301
302 ### response.end([data], [encoding])
303
304 This method signals to the server that all of the response headers and body
305 has been sent; that server should consider this message complete.
306 The method, `response.end()`, MUST be called on each
307 response.
308
309 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
310 followed by `response.end()`.
311
312
313 ## http.request(options, callback)
314
315 Node maintains several connections per server to make HTTP requests.
316 This function allows one to transparently issue requests.
317
318 Options:
319
320 - `host`: A domain name or IP address of the server to issue the request to.
321 - `port`: Port of remote server.
322 - `method`: A string specifing the HTTP request method. Possible values:
323   `'GET'` (default), `'POST'`, `'PUT'`, and `'DELETE'`.
324 - `path`: Request path. Should include query string and fragments if any.
325    E.G. `'/index.html?page=12'`
326 - `headers`: An object containing request headers.
327
328 `http.request()` returns an instance of the `http.ClientRequest`
329 class. The `ClientRequest` instance is a writable stream. If one needs to
330 upload a file with a POST request, then write to the `ClientRequest` object.
331
332 Example:
333
334     var options = {
335       host: 'www.google.com',
336       port: 80,
337       path: '/upload',
338       method: 'POST'
339     };
340
341     var req = http.request(options, function(res) {
342       console.log('STATUS: ' + res.statusCode);
343       console.log('HEADERS: ' + JSON.stringify(res.headers));
344       res.setEncoding('utf8');
345       res.on('data', function (chunk) {
346         console.log('BODY: ' + chunk);
347       });
348     });
349
350     // write data to request body
351     req.write('data\n');
352     req.write('data\n');
353     req.end();
354
355 Note that in the example `req.end()` was called. With `http.request()` one
356 must always call `req.end()` to signify that you're done with the request -
357 even if there is no data being written to the request body.
358
359 If any error is encountered during the request (be that with DNS resolution,
360 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
361 on the returned request object.
362
363 There are a few special headers that should be noted.
364
365 * Sending a 'Connection: keep-alive' will notify Node that the connection to
366   the server should be persisted until the next request.
367
368 * Sending a 'Content-length' header will disable the default chunked encoding.
369
370 * Sending an 'Expect' header will immediately send the request headers.
371   Usually, when sending 'Expect: 100-continue', you should both set a timeout
372   and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
373   information.
374
375 ## http.get(options, callback)
376
377 Since most requests are GET requests without bodies, Node provides this
378 convience method. The only difference between this method and `http.request()` is
379 that it sets the method to GET and calls `req.end()` automatically.
380
381 Example:
382
383     var options = {
384       host: 'www.google.com',
385       port: 80,
386       path: '/index.html'
387     };
388
389     http.get(options, function(res) {
390       console.log("Got response: " + res.statusCode);
391     }).on('error', function(e) {
392       console.log("Got error: " + e.message);
393     });
394
395
396 ## http.Agent
397
398 `http.request()` uses a special `Agent` for managing multiple connections to
399 an HTTP server. Normally `Agent` instances should not be exposed to user
400 code, however in certain situations it's useful to check the status of the
401 agent.
402
403 ### Event: 'upgrade'
404
405 `function (request, socket, head)`
406
407 Emitted each time a server responds to a request with an upgrade. If this event
408 isn't being listened for, clients receiving an upgrade header will have their
409 connections closed.
410
411 See the description of the `upgrade` event for `http.Server` for further details.
412
413 ### Event: 'continue'
414
415 `function ()`
416
417 Emitted when the server sends a '100 Continue' HTTP response, usually because
418 the request contained 'Expect: 100-continue'. This is an instruction that
419 the client should send the request body.
420
421 ### agent.maxSockets
422
423 By default set to 5. Determines how many concurrent sockets the agent can have open.
424
425 ### agent.sockets
426
427 An array of sockets currently inuse by the Agent. Do not modify.
428
429 ### agent.queue
430
431 A queue of requests waiting to be sent to sockets.
432
433
434
435 ## http.ClientRequest
436
437 This object is created internally and returned from `http.request()`.  It
438 represents an _in-progress_ request whose header has already been sent.
439
440 To get the response, add a listener for `'response'` to the request object.
441 `'response'` will be emitted from the request object when the response
442 headers have been received.  The `'response'` event is executed with one
443 argument which is an instance of `http.ClientResponse`.
444
445 During the `'response'` event, one can add listeners to the
446 response object; particularly to listen for the `'data'` event. Note that
447 the `'response'` event is called before any part of the response body is received,
448 so there is no need to worry about racing to catch the first part of the
449 body. As long as a listener for `'data'` is added during the `'response'`
450 event, the entire body will be caught.
451
452
453     // Good
454     request.on('response', function (response) {
455       response.on('data', function (chunk) {
456         console.log('BODY: ' + chunk);
457       });
458     });
459
460     // Bad - misses all or part of the body
461     request.on('response', function (response) {
462       setTimeout(function () {
463         response.on('data', function (chunk) {
464           console.log('BODY: ' + chunk);
465         });
466       }, 10);
467     });
468
469 This is a `Writable Stream`.
470
471 This is an `EventEmitter` with the following events:
472
473 ### Event 'response'
474
475 `function (response) { }`
476
477 Emitted when a response is received to this request. This event is emitted only once. The
478 `response` argument will be an instance of `http.ClientResponse`.
479
480
481 ### request.write(chunk, encoding='utf8')
482
483 Sends a chunk of the body.  By calling this method
484 many times, the user can stream a request body to a
485 server--in that case it is suggested to use the
486 `['Transfer-Encoding', 'chunked']` header line when
487 creating the request.
488
489 The `chunk` argument should be an array of integers
490 or a string.
491
492 The `encoding` argument is optional and only
493 applies when `chunk` is a string.
494
495
496 ### request.end([data], [encoding])
497
498 Finishes sending the request. If any parts of the body are
499 unsent, it will flush them to the stream. If the request is
500 chunked, this will send the terminating `'0\r\n\r\n'`.
501
502 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
503 followed by `request.end()`.
504
505
506 ## http.ClientResponse
507
508 This object is created when making a request with `http.request()`. It is
509 passed to the `'response'` event of the request object.
510
511 The response implements the `Readable Stream` interface.
512
513 ### Event: 'data'
514
515 `function (chunk) {}`
516
517 Emitted when a piece of the message body is received.
518
519
520 ### Event: 'end'
521
522 `function () {}`
523
524 Emitted exactly once for each message. No arguments. After
525 emitted no other events will be emitted on the response.
526
527 ### response.statusCode
528
529 The 3-digit HTTP response status code. E.G. `404`.
530
531 ### response.httpVersion
532
533 The HTTP version of the connected-to server. Probably either
534 `'1.1'` or `'1.0'`.
535 Also `response.httpVersionMajor` is the first integer and
536 `response.httpVersionMinor` is the second.
537
538 ### response.headers
539
540 The response headers object.
541
542 ### response.trailers
543
544 The response trailers object. Only populated after the 'end' event.
545
546 ### response.setEncoding(encoding=null)
547
548 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
549 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
550
551 ### response.pause()
552
553 Pauses response from emitting events.  Useful to throttle back a download.
554
555 ### response.resume()
556
557 Resumes a paused response.