Add support for Unix Domain Sockets to HTTP
[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 (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: '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 message. No arguments.  After
146 emitted no other events will be emitted on the request.
147
148
149 ### request.method
150
151 The request method as a string. Read only. Example:
152 `'GET'`, `'DELETE'`.
153
154
155 ### request.url
156
157 Request URL string. This contains only the URL that is
158 present in the actual HTTP request. If the request is:
159
160     GET /status?name=ryan HTTP/1.1\r\n
161     Accept: text/plain\r\n
162     \r\n
163
164 Then `request.url` will be:
165
166     '/status?name=ryan'
167
168 If you would like to parse the URL into its parts, you can use
169 `require('url').parse(request.url)`.  Example:
170
171     node> require('url').parse('/status?name=ryan')
172     { href: '/status?name=ryan',
173       search: '?name=ryan',
174       query: 'name=ryan',
175       pathname: '/status' }
176
177 If you would like to extract the params from the query string,
178 you can use the `require('querystring').parse` function, or pass
179 `true` as the second argument to `require('url').parse`.  Example:
180
181     node> require('url').parse('/status?name=ryan', true)
182     { href: '/status?name=ryan',
183       search: '?name=ryan',
184       query: { name: 'ryan' },
185       pathname: '/status' }
186
187
188
189 ### request.headers
190
191 Read only.
192
193 ### request.trailers
194
195 Read only; HTTP trailers (if present). Only populated after the 'end' event.
196
197 ### request.httpVersion
198
199 The HTTP protocol version as a string. Read only. Examples:
200 `'1.1'`, `'1.0'`.
201 Also `request.httpVersionMajor` is the first integer and
202 `request.httpVersionMinor` is the second.
203
204
205 ### request.setEncoding(encoding=null)
206
207 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
208 to `null`, which means that the `'data'` event will emit a `Buffer` object..
209
210
211 ### request.pause()
212
213 Pauses request from emitting events.  Useful to throttle back an upload.
214
215
216 ### request.resume()
217
218 Resumes a paused request.
219
220 ### request.connection
221
222 The `net.Stream` object associated with the connection.
223
224
225 With HTTPS support, use request.connection.verifyPeer() and
226 request.connection.getPeerCertificate() to obtain the client's
227 authentication details.
228
229
230
231 ## http.ServerResponse
232
233 This object is created internally by a HTTP server--not by the user. It is
234 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
235
236 ### response.writeContinue()
237
238 Sends a HTTP/1.1 100 Continue message to the client, indicating that
239 the request body should be sent. See the [checkContinue](#event_checkContinue_) event on
240 `Server`.
241
242 ### response.writeHead(statusCode, [reasonPhrase], [headers])
243
244 Sends a response header to the request. The status code is a 3-digit HTTP
245 status code, like `404`. The last argument, `headers`, are the response headers.
246 Optionally one can give a human-readable `reasonPhrase` as the second
247 argument.
248
249 Example:
250
251     var body = 'hello world';
252     response.writeHead(200, {
253       'Content-Length': body.length,
254       'Content-Type': 'text/plain' });
255
256 This method must only be called once on a message and it must
257 be called before `response.end()` is called.
258
259 If you call `response.write()` or `response.end()` before calling this, the
260 implicit/mutable headers will be calculated and call this function for you.
261
262 Note: that Content-Length is given in bytes not characters. The above example
263 works because the string `'hello world'` contains only single byte characters.
264 If the body contains higher coded characters then `Buffer.byteLength()`
265 should be used to determine the number of bytes in a given encoding.
266
267 ### response.statusCode
268
269 When using implicit headers (not calling `response.writeHead()` explicitly), this property
270 controls the status code that will be send to the client when the headers get
271 flushed.
272
273 Example:
274
275     response.statusCode = 404;
276
277 ### response.setHeader(name, value)
278
279 Sets a single header value for implicit headers.  If this header already exists
280 in the to-be-sent headers, it's value will be replaced.  Use an array of strings
281 here if you need to send multiple headers with the same name.
282
283 Example:
284
285     response.setHeader("Content-Type", "text/html");
286
287 or
288
289     response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
290
291
292 ### response.getHeader(name)
293
294 Reads out a header that's already been queued but not sent to the client.  Note
295 that the name is case insensitive.  This can only be called before headers get
296 implicitly flushed.
297
298 Example:
299
300     var contentType = response.getHeader('content-type');
301
302 ### response.removeHeader(name)
303
304 Removes a header that's queued for implicit sending.
305
306 Example:
307
308     response.removeHeader("Content-Encoding");
309
310
311 ### response.write(chunk, encoding='utf8')
312
313 If this method is called and `response.writeHead()` has not been called, it will
314 switch to implicit header mode and flush the implicit headers.
315
316 This sends a chunk of the response body. This method may
317 be called multiple times to provide successive parts of the body.
318
319 `chunk` can be a string or a buffer. If `chunk` is a string,
320 the second parameter specifies how to encode it into a byte stream.
321 By default the `encoding` is `'utf8'`.
322
323 **Note**: This is the raw HTTP body and has nothing to do with
324 higher-level multi-part body encodings that may be used.
325
326 The first time `response.write()` is called, it will send the buffered
327 header information and the first body to the client. The second time
328 `response.write()` is called, Node assumes you're going to be streaming
329 data, and sends that separately. That is, the response is buffered up to the
330 first chunk of body.
331
332 ### response.addTrailers(headers)
333
334 This method adds HTTP trailing headers (a header but at the end of the
335 message) to the response.
336
337 Trailers will **only** be emitted if chunked encoding is used for the
338 response; if it is not (e.g., if the request was HTTP/1.0), they will
339 be silently discarded.
340
341 Note that HTTP requires the `Trailer` header to be sent if you intend to
342 emit trailers, with a list of the header fields in its value. E.g.,
343
344     response.writeHead(200, { 'Content-Type': 'text/plain',
345                               'Trailer': 'TraceInfo' });
346     response.write(fileData);
347     response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
348     response.end();
349
350
351 ### response.end([data], [encoding])
352
353 This method signals to the server that all of the response headers and body
354 has been sent; that server should consider this message complete.
355 The method, `response.end()`, MUST be called on each
356 response.
357
358 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
359 followed by `response.end()`.
360
361
362 ## http.request(options, callback)
363
364 Node maintains several connections per server to make HTTP requests.
365 This function allows one to transparently issue requests.
366
367 Options:
368
369 - `host`: A domain name or IP address of the server to issue the request to.
370 - `port`: Port of remote server.
371 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
372 - `method`: A string specifying the HTTP request method. Possible values:
373   `'GET'` (default), `'POST'`, `'PUT'`, and `'DELETE'`.
374 - `path`: Request path. Should include query string and fragments if any.
375    E.G. `'/index.html?page=12'`
376 - `headers`: An object containing request headers.
377
378 `http.request()` returns an instance of the `http.ClientRequest`
379 class. The `ClientRequest` instance is a writable stream. If one needs to
380 upload a file with a POST request, then write to the `ClientRequest` object.
381
382 Example:
383
384     var options = {
385       host: 'www.google.com',
386       port: 80,
387       path: '/upload',
388       method: 'POST'
389     };
390
391     var req = http.request(options, function(res) {
392       console.log('STATUS: ' + res.statusCode);
393       console.log('HEADERS: ' + JSON.stringify(res.headers));
394       res.setEncoding('utf8');
395       res.on('data', function (chunk) {
396         console.log('BODY: ' + chunk);
397       });
398     });
399
400     // write data to request body
401     req.write('data\n');
402     req.write('data\n');
403     req.end();
404
405 Note that in the example `req.end()` was called. With `http.request()` one
406 must always call `req.end()` to signify that you're done with the request -
407 even if there is no data being written to the request body.
408
409 If any error is encountered during the request (be that with DNS resolution,
410 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
411 on the returned request object.
412
413 There are a few special headers that should be noted.
414
415 * Sending a 'Connection: keep-alive' will notify Node that the connection to
416   the server should be persisted until the next request.
417
418 * Sending a 'Content-length' header will disable the default chunked encoding.
419
420 * Sending an 'Expect' header will immediately send the request headers.
421   Usually, when sending 'Expect: 100-continue', you should both set a timeout
422   and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
423   information.
424
425 ## http.get(options, callback)
426
427 Since most requests are GET requests without bodies, Node provides this
428 convenience method. The only difference between this method and `http.request()` is
429 that it sets the method to GET and calls `req.end()` automatically.
430
431 Example:
432
433     var options = {
434       host: 'www.google.com',
435       port: 80,
436       path: '/index.html'
437     };
438
439     http.get(options, function(res) {
440       console.log("Got response: " + res.statusCode);
441     }).on('error', function(e) {
442       console.log("Got error: " + e.message);
443     });
444
445
446 ## http.Agent
447 ## http.getAgent(options)
448
449 `http.request()` uses a special `Agent` for managing multiple connections to
450 an HTTP server. Normally `Agent` instances should not be exposed to user
451 code, however in certain situations it's useful to check the status of the
452 agent. The `http.getAgent()` function allows you to access the agents.
453
454 Options:
455
456 - `host`: A domain name or IP address of the server to issue the request to.
457 - `port`: Port of remote server.
458 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
459
460 ### Event: 'upgrade'
461
462 `function (request, socket, head)`
463
464 Emitted each time a server responds to a request with an upgrade. If this event
465 isn't being listened for, clients receiving an upgrade header will have their
466 connections closed.
467
468 See the description of the [upgrade event](http.html#event_upgrade_) for `http.Server` for further details.
469
470 ### Event: 'continue'
471
472 `function ()`
473
474 Emitted when the server sends a '100 Continue' HTTP response, usually because
475 the request contained 'Expect: 100-continue'. This is an instruction that
476 the client should send the request body.
477
478 ### agent.maxSockets
479
480 By default set to 5. Determines how many concurrent sockets the agent can have open.
481
482 ### agent.sockets
483
484 An array of sockets currently in use by the Agent. Do not modify.
485
486 ### agent.queue
487
488 A queue of requests waiting to be sent to sockets.
489
490
491
492 ## http.ClientRequest
493
494 This object is created internally and returned from `http.request()`.  It
495 represents an _in-progress_ request whose header has already been queued.  The
496 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
497 `removeHeader(name)` API.  The actual header will be sent along with the first
498 data chunk or when closing the connection.
499
500 To get the response, add a listener for `'response'` to the request object.
501 `'response'` will be emitted from the request object when the response
502 headers have been received.  The `'response'` event is executed with one
503 argument which is an instance of `http.ClientResponse`.
504
505 During the `'response'` event, one can add listeners to the
506 response object; particularly to listen for the `'data'` event. Note that
507 the `'response'` event is called before any part of the response body is received,
508 so there is no need to worry about racing to catch the first part of the
509 body. As long as a listener for `'data'` is added during the `'response'`
510 event, the entire body will be caught.
511
512
513     // Good
514     request.on('response', function (response) {
515       response.on('data', function (chunk) {
516         console.log('BODY: ' + chunk);
517       });
518     });
519
520     // Bad - misses all or part of the body
521     request.on('response', function (response) {
522       setTimeout(function () {
523         response.on('data', function (chunk) {
524           console.log('BODY: ' + chunk);
525         });
526       }, 10);
527     });
528
529 This is a `Writable Stream`.
530
531 This is an `EventEmitter` with the following events:
532
533 ### Event 'response'
534
535 `function (response) { }`
536
537 Emitted when a response is received to this request. This event is emitted only once. The
538 `response` argument will be an instance of `http.ClientResponse`.
539
540
541 ### request.write(chunk, encoding='utf8')
542
543 Sends a chunk of the body.  By calling this method
544 many times, the user can stream a request body to a
545 server--in that case it is suggested to use the
546 `['Transfer-Encoding', 'chunked']` header line when
547 creating the request.
548
549 The `chunk` argument should be an array of integers
550 or a string.
551
552 The `encoding` argument is optional and only
553 applies when `chunk` is a string.
554
555
556 ### request.end([data], [encoding])
557
558 Finishes sending the request. If any parts of the body are
559 unsent, it will flush them to the stream. If the request is
560 chunked, this will send the terminating `'0\r\n\r\n'`.
561
562 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
563 followed by `request.end()`.
564
565 ### request.abort()
566
567 Aborts a request.  (New since v0.3.8.)
568
569
570 ## http.ClientResponse
571
572 This object is created when making a request with `http.request()`. It is
573 passed to the `'response'` event of the request object.
574
575 The response implements the `Readable Stream` interface.
576
577 ### Event: 'data'
578
579 `function (chunk) {}`
580
581 Emitted when a piece of the message body is received.
582
583
584 ### Event: 'end'
585
586 `function () {}`
587
588 Emitted exactly once for each message. No arguments. After
589 emitted no other events will be emitted on the response.
590
591 ### response.statusCode
592
593 The 3-digit HTTP response status code. E.G. `404`.
594
595 ### response.httpVersion
596
597 The HTTP version of the connected-to server. Probably either
598 `'1.1'` or `'1.0'`.
599 Also `response.httpVersionMajor` is the first integer and
600 `response.httpVersionMinor` is the second.
601
602 ### response.headers
603
604 The response headers object.
605
606 ### response.trailers
607
608 The response trailers object. Only populated after the 'end' event.
609
610 ### response.setEncoding(encoding=null)
611
612 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
613 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
614
615 ### response.pause()
616
617 Pauses response from emitting events.  Useful to throttle back a download.
618
619 ### response.resume()
620
621 Resumes a paused response.