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