Merge branch 'v0.4'
[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 Emitted each time there is request. Note that there may be multiple requests
35 per connection (in the case of keep-alive connections).
36  `request` is an instance of `http.ServerRequest` and `response` is
37  an instance of `http.ServerResponse`
38
39 ### Event: 'connection'
40
41 `function (socket) { }`
42
43  When a new TCP stream is established. `socket` is an object of type
44  `net.Socket`. Usually users will not want to access this event. The
45  `socket` 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: 'checkContinue'
54
55 `function (request, response) { }`
56
57 Emitted each time a request with an http Expect: 100-continue is received.
58 If this event isn't listened for, the server will automatically respond
59 with a 100 Continue as appropriate.
60
61 Handling this event involves calling `response.writeContinue` if the client
62 should continue to send the request body, or generating an appropriate HTTP
63 response (e.g., 400 Bad Request) if the client should not continue to send the
64 request body.
65
66 Note that when this event is emitted and handled, the `request` event will
67 not be emitted.
68
69 ### Event: 'upgrade'
70
71 `function (request, socket, head) { }`
72
73 Emitted each time a client requests a http upgrade. If this event isn't
74 listened for, then clients requesting an upgrade will have their connections
75 closed.
76
77 * `request` is the arguments for the http request, as it is in the request event.
78 * `socket` is the network socket between the server and client.
79 * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
80
81 After this event is emitted, the request's socket will not have a `data`
82 event listener, meaning you will need to bind to it in order to handle data
83 sent to the server on that socket.
84
85 ### Event: 'clientError'
86
87 `function (exception) { }`
88
89 If a client connection emits an 'error' event - it will forwarded here.
90
91 ### http.createServer([requestListener])
92
93 Returns a new web server object.
94
95 The `requestListener` is a function which is automatically
96 added to the `'request'` event.
97
98 ### server.listen(port, [hostname], [callback])
99
100 Begin accepting connections on the specified port and hostname.  If the
101 hostname is omitted, the server will accept connections directed to any
102 IPv4 address (`INADDR_ANY`).
103
104 To listen to a unix socket, supply a filename instead of port and hostname.
105
106 This function is asynchronous. The last parameter `callback` will be called
107 when the server has been bound to the port.
108
109
110 ### server.listen(path, [callback])
111
112 Start a UNIX socket server listening for connections on the given `path`.
113
114 This function is asynchronous. The last parameter `callback` will be called
115 when the server has been bound.
116
117
118 ### server.close()
119
120 Stops the server from accepting new connections.
121
122
123 ## http.ServerRequest
124
125 This object is created internally by a HTTP server -- not by
126 the user -- and passed as the first argument to a `'request'` listener.
127
128 This is an `EventEmitter` with the following events:
129
130 ### Event: 'data'
131
132 `function (chunk) { }`
133
134 Emitted when a piece of the message body is received.
135
136 Example: A chunk of the body is given as the single
137 argument. The transfer-encoding has been decoded.  The
138 body chunk is a string.  The body encoding is set with
139 `request.setEncoding()`.
140
141 ### Event: 'end'
142
143 `function () { }`
144
145 Emitted exactly once for each request. After that, no more `'data'` events
146 will be emitted on the request.
147
148 ### Event: 'close'
149
150 `function (err) { }`
151
152 Indicates that the underlaying connection was terminated before
153 `response.end()` was called or able to flush.
154
155 The `err` parameter is always present and indicates the reason for the timeout:
156
157 `err.code === 'timeout'` indicates that the underlaying connection timed out.
158 This may happen because all incoming connections have a default timeout of 2
159 minutes.
160
161 `err.code === 'aborted'` means that the client has closed the underlaying
162 connection prematurely.
163
164 Just like `'end'`, this event occurs only once per request, and no more `'data'`
165 events will fire afterwards.
166
167 Note: `'close'` can fire after `'end'`, but not vice versa.
168
169 ### request.method
170
171 The request method as a string. Read only. Example:
172 `'GET'`, `'DELETE'`.
173
174
175 ### request.url
176
177 Request URL string. This contains only the URL that is
178 present in the actual HTTP request. If the request is:
179
180     GET /status?name=ryan HTTP/1.1\r\n
181     Accept: text/plain\r\n
182     \r\n
183
184 Then `request.url` will be:
185
186     '/status?name=ryan'
187
188 If you would like to parse the URL into its parts, you can use
189 `require('url').parse(request.url)`.  Example:
190
191     node> require('url').parse('/status?name=ryan')
192     { href: '/status?name=ryan',
193       search: '?name=ryan',
194       query: 'name=ryan',
195       pathname: '/status' }
196
197 If you would like to extract the params from the query string,
198 you can use the `require('querystring').parse` function, or pass
199 `true` as the second argument to `require('url').parse`.  Example:
200
201     node> require('url').parse('/status?name=ryan', true)
202     { href: '/status?name=ryan',
203       search: '?name=ryan',
204       query: { name: 'ryan' },
205       pathname: '/status' }
206
207
208
209 ### request.headers
210
211 Read only.
212
213 ### request.trailers
214
215 Read only; HTTP trailers (if present). Only populated after the 'end' event.
216
217 ### request.httpVersion
218
219 The HTTP protocol version as a string. Read only. Examples:
220 `'1.1'`, `'1.0'`.
221 Also `request.httpVersionMajor` is the first integer and
222 `request.httpVersionMinor` is the second.
223
224
225 ### request.setEncoding(encoding=null)
226
227 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
228 to `null`, which means that the `'data'` event will emit a `Buffer` object..
229
230
231 ### request.pause()
232
233 Pauses request from emitting events.  Useful to throttle back an upload.
234
235
236 ### request.resume()
237
238 Resumes a paused request.
239
240 ### request.connection
241
242 The `net.Socket` object associated with the connection.
243
244
245 With HTTPS support, use request.connection.verifyPeer() and
246 request.connection.getPeerCertificate() to obtain the client's
247 authentication details.
248
249
250
251 ## http.ServerResponse
252
253 This object is created internally by a HTTP server--not by the user. It is
254 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
255
256 ### response.writeContinue()
257
258 Sends a HTTP/1.1 100 Continue message to the client, indicating that
259 the request body should be sent. See the [checkContinue](#event_checkContinue_) event on
260 `Server`.
261
262 ### response.writeHead(statusCode, [reasonPhrase], [headers])
263
264 Sends a response header to the request. The status code is a 3-digit HTTP
265 status code, like `404`. The last argument, `headers`, are the response headers.
266 Optionally one can give a human-readable `reasonPhrase` as the second
267 argument.
268
269 Example:
270
271     var body = 'hello world';
272     response.writeHead(200, {
273       'Content-Length': body.length,
274       'Content-Type': 'text/plain' });
275
276 This method must only be called once on a message and it must
277 be called before `response.end()` is called.
278
279 If you call `response.write()` or `response.end()` before calling this, the
280 implicit/mutable headers will be calculated and call this function for you.
281
282 Note: that Content-Length is given in bytes not characters. The above example
283 works because the string `'hello world'` contains only single byte characters.
284 If the body contains higher coded characters then `Buffer.byteLength()`
285 should be used to determine the number of bytes in a given encoding.
286 And Node does not check whether Content-Length and the length of the body
287 which has been transmitted are equal or not.
288
289 ### response.statusCode
290
291 When using implicit headers (not calling `response.writeHead()` explicitly), this property
292 controls the status code that will be send to the client when the headers get
293 flushed.
294
295 Example:
296
297     response.statusCode = 404;
298
299 After response header was sent to the client, this property indicates the
300 status code which was sent out.
301
302 ### response.setHeader(name, value)
303
304 Sets a single header value for implicit headers.  If this header already exists
305 in the to-be-sent headers, it's value will be replaced.  Use an array of strings
306 here if you need to send multiple headers with the same name.
307
308 Example:
309
310     response.setHeader("Content-Type", "text/html");
311
312 or
313
314     response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
315
316
317 ### response.getHeader(name)
318
319 Reads out a header that's already been queued but not sent to the client.  Note
320 that the name is case insensitive.  This can only be called before headers get
321 implicitly flushed.
322
323 Example:
324
325     var contentType = response.getHeader('content-type');
326
327 ### response.removeHeader(name)
328
329 Removes a header that's queued for implicit sending.
330
331 Example:
332
333     response.removeHeader("Content-Encoding");
334
335
336 ### response.write(chunk, encoding='utf8')
337
338 If this method is called and `response.writeHead()` has not been called, it will
339 switch to implicit header mode and flush the implicit headers.
340
341 This sends a chunk of the response body. This method may
342 be called multiple times to provide successive parts of the body.
343
344 `chunk` can be a string or a buffer. If `chunk` is a string,
345 the second parameter specifies how to encode it into a byte stream.
346 By default the `encoding` is `'utf8'`.
347
348 **Note**: This is the raw HTTP body and has nothing to do with
349 higher-level multi-part body encodings that may be used.
350
351 The first time `response.write()` is called, it will send the buffered
352 header information and the first body to the client. The second time
353 `response.write()` is called, Node assumes you're going to be streaming
354 data, and sends that separately. That is, the response is buffered up to the
355 first chunk of body.
356
357 ### response.addTrailers(headers)
358
359 This method adds HTTP trailing headers (a header but at the end of the
360 message) to the response.
361
362 Trailers will **only** be emitted if chunked encoding is used for the
363 response; if it is not (e.g., if the request was HTTP/1.0), they will
364 be silently discarded.
365
366 Note that HTTP requires the `Trailer` header to be sent if you intend to
367 emit trailers, with a list of the header fields in its value. E.g.,
368
369     response.writeHead(200, { 'Content-Type': 'text/plain',
370                               'Trailer': 'TraceInfo' });
371     response.write(fileData);
372     response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
373     response.end();
374
375
376 ### response.end([data], [encoding])
377
378 This method signals to the server that all of the response headers and body
379 has been sent; that server should consider this message complete.
380 The method, `response.end()`, MUST be called on each
381 response.
382
383 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
384 followed by `response.end()`.
385
386
387 ## http.request(options, callback)
388
389 Node maintains several connections per server to make HTTP requests.
390 This function allows one to transparently issue requests.
391
392 Options:
393
394 - `host`: A domain name or IP address of the server to issue the request to.
395 - `port`: Port of remote server.
396 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
397 - `method`: A string specifying the HTTP request method. Possible values:
398   `'GET'` (default), `'POST'`, `'PUT'`, and `'DELETE'`.
399 - `path`: Request path. Should include query string and fragments if any.
400    E.G. `'/index.html?page=12'`
401 - `headers`: An object containing request headers.
402 - `agent`: Controls `Agent` behavior. When an Agent is used request will default to Connection:keep-alive. Possible values:
403  - `undefined` (default): use default `Agent` for this host and port.
404  - `Agent` object: explicitly use the passed in `Agent`.
405  - `false`: opts out of connection pooling with an Agent, defaults request to Connection:close.
406
407 `http.request()` returns an instance of the `http.ClientRequest`
408 class. The `ClientRequest` instance is a writable stream. If one needs to
409 upload a file with a POST request, then write to the `ClientRequest` object.
410
411 Example:
412
413     var options = {
414       host: 'www.google.com',
415       port: 80,
416       path: '/upload',
417       method: 'POST'
418     };
419
420     var req = http.request(options, function(res) {
421       console.log('STATUS: ' + res.statusCode);
422       console.log('HEADERS: ' + JSON.stringify(res.headers));
423       res.setEncoding('utf8');
424       res.on('data', function (chunk) {
425         console.log('BODY: ' + chunk);
426       });
427     });
428
429     req.on('error', function(e) {
430       console.log('problem with request: ' + e.message);
431     });
432
433     // write data to request body
434     req.write('data\n');
435     req.write('data\n');
436     req.end();
437
438 Note that in the example `req.end()` was called. With `http.request()` one
439 must always call `req.end()` to signify that you're done with the request -
440 even if there is no data being written to the request body.
441
442 If any error is encountered during the request (be that with DNS resolution,
443 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
444 on the returned request object.
445
446 There are a few special headers that should be noted.
447
448 * Sending a 'Connection: keep-alive' will notify Node that the connection to
449   the server should be persisted until the next request.
450
451 * Sending a 'Content-length' header will disable the default chunked encoding.
452
453 * Sending an 'Expect' header will immediately send the request headers.
454   Usually, when sending 'Expect: 100-continue', you should both set a timeout
455   and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
456   information.
457
458 ## http.get(options, callback)
459
460 Since most requests are GET requests without bodies, Node provides this
461 convenience method. The only difference between this method and `http.request()` is
462 that it sets the method to GET and calls `req.end()` automatically.
463
464 Example:
465
466     var options = {
467       host: 'www.google.com',
468       port: 80,
469       path: '/index.html'
470     };
471
472     http.get(options, function(res) {
473       console.log("Got response: " + res.statusCode);
474     }).on('error', function(e) {
475       console.log("Got error: " + e.message);
476     });
477
478
479 ## http.Agent
480
481 ## http.globalAgent
482
483 Global instance of Agent which is used as the default for all http client requests.
484
485 ### agent.maxSockets
486
487 By default set to 5. Determines how many concurrent sockets the agent can have open per host.
488
489 ### agent.sockets
490
491 An object which contains arrays of sockets currently in use by the Agent. Do not modify.
492
493 ### agent.requests
494
495 An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
496
497
498 ## http.ClientRequest
499
500 This object is created internally and returned from `http.request()`.  It
501 represents an _in-progress_ request whose header has already been queued.  The
502 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
503 `removeHeader(name)` API.  The actual header will be sent along with the first
504 data chunk or when closing the connection.
505
506 To get the response, add a listener for `'response'` to the request object.
507 `'response'` will be emitted from the request object when the response
508 headers have been received.  The `'response'` event is executed with one
509 argument which is an instance of `http.ClientResponse`.
510
511 During the `'response'` event, one can add listeners to the
512 response object; particularly to listen for the `'data'` event. Note that
513 the `'response'` event is called before any part of the response body is received,
514 so there is no need to worry about racing to catch the first part of the
515 body. As long as a listener for `'data'` is added during the `'response'`
516 event, the entire body will be caught.
517
518
519     // Good
520     request.on('response', function (response) {
521       response.on('data', function (chunk) {
522         console.log('BODY: ' + chunk);
523       });
524     });
525
526     // Bad - misses all or part of the body
527     request.on('response', function (response) {
528       setTimeout(function () {
529         response.on('data', function (chunk) {
530           console.log('BODY: ' + chunk);
531         });
532       }, 10);
533     });
534
535 This is a `Writable Stream`.
536 Note: Node does not check whether Content-Length and the length of the body
537 which has been transmitted are equal or not.
538
539 This is an `EventEmitter` with the following events:
540
541 ### Event 'response'
542
543 `function (response) { }`
544
545 Emitted when a response is received to this request. This event is emitted only once. The
546 `response` argument will be an instance of `http.ClientResponse`.
547
548 Options:
549
550 - `host`: A domain name or IP address of the server to issue the request to.
551 - `port`: Port of remote server.
552 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
553
554 ### Event: 'socket'
555
556 `function (socket) { }`
557
558 Emitted after a socket is assigned to this request.
559
560 ### Event: 'upgrade'
561
562 `function (response, socket, head) { }`
563
564 Emitted each time a server responds to a request with an upgrade. If this
565 event isn't being listened for, clients receiving an upgrade header will have
566 their connections closed.
567
568 A client server pair that show you how to listen for the `upgrade` event using `http.getAgent`:
569
570     var http = require('http');
571     var net = require('net');
572
573     // Create an HTTP server
574     var srv = http.createServer(function (req, res) {
575       res.writeHead(200, {'Content-Type': 'text/plain'});
576       res.end('okay');
577     });
578     srv.on('upgrade', function(req, socket, upgradeHead) {
579       socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
580                    'Upgrade: WebSocket\r\n' +
581                    'Connection: Upgrade\r\n' +
582                    '\r\n\r\n');
583
584       socket.ondata = function(data, start, end) {
585         socket.write(data.toString('utf8', start, end), 'utf8'); // echo back
586       };
587     });
588
589     // now that server is running
590     srv.listen(1337, '127.0.0.1', function() {
591
592       // make a request
593       var options = {
594         port: 1337,
595         host: '127.0.0.1',
596         headers: {
597           'Connection': 'Upgrade',
598           'Upgrade': 'websocket'
599         }
600       };
601
602       var req = http.request(options);
603       req.end();
604
605       req.on('upgrade', function(res, socket, upgradeHead) {
606         console.log('got upgraded!');
607         socket.end();
608         process.exit(0);
609       });
610     });
611
612 ### Event: 'continue'
613
614 `function ()`
615
616 Emitted when the server sends a '100 Continue' HTTP response, usually because
617 the request contained 'Expect: 100-continue'. This is an instruction that
618 the client should send the request body.
619
620 ### request.write(chunk, encoding='utf8')
621
622 Sends a chunk of the body.  By calling this method
623 many times, the user can stream a request body to a
624 server--in that case it is suggested to use the
625 `['Transfer-Encoding', 'chunked']` header line when
626 creating the request.
627
628 The `chunk` argument should be an array of integers
629 or a string.
630
631 The `encoding` argument is optional and only
632 applies when `chunk` is a string.
633
634
635 ### request.end([data], [encoding])
636
637 Finishes sending the request. If any parts of the body are
638 unsent, it will flush them to the stream. If the request is
639 chunked, this will send the terminating `'0\r\n\r\n'`.
640
641 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
642 followed by `request.end()`.
643
644 ### request.abort()
645
646 Aborts a request.  (New since v0.3.8.)
647
648
649 ## http.ClientResponse
650
651 This object is created when making a request with `http.request()`. It is
652 passed to the `'response'` event of the request object.
653
654 The response implements the `Readable Stream` interface.
655
656 ### Event: 'data'
657
658 `function (chunk) { }`
659
660 Emitted when a piece of the message body is received.
661
662
663 ### Event: 'end'
664
665 `function () { }`
666
667 Emitted exactly once for each message. No arguments. After
668 emitted no other events will be emitted on the response.
669
670 ### Event: 'close'
671
672 `function (err) { }`
673
674 Indicates that the underlaying connection was terminated before
675 `end` event was emitted.
676 See [http.ServerRequest](#http.ServerRequest)'s `'close'` event for more
677 information.
678
679 ### response.statusCode
680
681 The 3-digit HTTP response status code. E.G. `404`.
682
683 ### response.httpVersion
684
685 The HTTP version of the connected-to server. Probably either
686 `'1.1'` or `'1.0'`.
687 Also `response.httpVersionMajor` is the first integer and
688 `response.httpVersionMinor` is the second.
689
690 ### response.headers
691
692 The response headers object.
693
694 ### response.trailers
695
696 The response trailers object. Only populated after the 'end' event.
697
698 ### response.setEncoding(encoding=null)
699
700 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
701 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
702
703 ### response.pause()
704
705 Pauses response from emitting events.  Useful to throttle back a download.
706
707 ### response.resume()
708
709 Resumes a paused response.