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