e94f631ad6c57c38c077852620045b114911a367
[platform/upstream/nodejs.git] / doc / api / http.markdown
1 # HTTP
2
3     Stability: 3 - Stable
4
5 To use the HTTP server and client one must `require('http')`.
6
7 The HTTP interfaces in Node are designed to support many features
8 of the protocol which have been traditionally difficult to use.
9 In particular, large, possibly chunk-encoded, messages. The interface is
10 careful to never buffer entire requests or responses--the
11 user is able to stream data.
12
13 HTTP message headers are represented by an object like this:
14
15     { 'content-length': '123',
16       'content-type': 'text/plain',
17       'connection': 'keep-alive',
18       'host': 'mysite.com',
19       'accept': '*/*' }
20
21 Keys are lowercased. Values are not modified.
22
23 In order to support the full spectrum of possible HTTP applications, Node's
24 HTTP API is very low-level. It deals with stream handling and message
25 parsing only. It parses a message into headers and body but it does not
26 parse the actual headers or the body.
27
28 Defined headers that allow multiple values are concatenated with a `,`
29 character, except for the `set-cookie` and `cookie` headers which are
30 represented as an array of values.  Headers such as `content-length`
31 which can only have a single value are parsed accordingly, and only a
32 single value is represented on the parsed object.
33
34 The raw headers as they were received are retained in the `rawHeaders`
35 property, which is an array of `[key, value, key2, value2, ...]`.  For
36 example, the previous message header object might have a `rawHeaders`
37 list like the following:
38
39     [ 'ConTent-Length', '123456',
40       'content-LENGTH', '123',
41       'content-type', 'text/plain',
42       'CONNECTION', 'keep-alive',
43       'Host', 'mysite.com',
44       'accepT', '*/*' ]
45
46 ## http.METHODS
47
48 * {Array}
49
50 A list of the HTTP methods that are supported by the parser.
51
52 ## http.STATUS_CODES
53
54 * {Object}
55
56 A collection of all the standard HTTP response status codes, and the
57 short description of each.  For example, `http.STATUS_CODES[404] === 'Not
58 Found'`.
59
60 ## http.createServer([requestListener])
61
62 Returns a new web server object.
63
64 The `requestListener` is a function which is automatically
65 added to the `'request'` event.
66
67 ## http.createClient([port]\[, host])
68
69 This function is **deprecated**; please use [http.request()][] instead.
70 Constructs a new HTTP client. `port` and `host` refer to the server to be
71 connected to.
72
73 ## Class: http.Server
74
75 This is an [EventEmitter][] with the following events:
76
77 ### Event: 'request'
78
79 `function (request, response) { }`
80
81 Emitted each time there is a request. Note that there may be multiple requests
82 per connection (in the case of keep-alive connections).
83  `request` is an instance of [http.IncomingMessage][] and `response` is
84 an instance of [http.ServerResponse][].
85
86 ### Event: 'connection'
87
88 `function (socket) { }`
89
90 When a new TCP stream is established. `socket` is an object of type
91 `net.Socket`. Usually users will not want to access this event. In
92 particular, the socket will not emit `readable` events because of how
93 the protocol parser attaches to the socket. The `socket` can also be
94 accessed at `request.connection`.
95
96 ### Event: 'close'
97
98 `function () { }`
99
100 Emitted when the server closes.
101
102 ### Event: 'checkContinue'
103
104 `function (request, response) { }`
105
106 Emitted each time a request with an http Expect: 100-continue is received.
107 If this event isn't listened for, the server will automatically respond
108 with a 100 Continue as appropriate.
109
110 Handling this event involves calling [response.writeContinue()][] if the client
111 should continue to send the request body, or generating an appropriate HTTP
112 response (e.g., 400 Bad Request) if the client should not continue to send the
113 request body.
114
115 Note that when this event is emitted and handled, the `request` event will
116 not be emitted.
117
118 ### Event: 'connect'
119
120 `function (request, socket, head) { }`
121
122 Emitted each time a client requests a http CONNECT method. If this event isn't
123 listened for, then clients requesting a CONNECT method will have their
124 connections closed.
125
126 * `request` is the arguments for the http request, as it is in the request
127   event.
128 * `socket` is the network socket between the server and client.
129 * `head` is an instance of Buffer, the first packet of the tunneling stream,
130   this may be empty.
131
132 After this event is emitted, the request's socket will not have a `data`
133 event listener, meaning you will need to bind to it in order to handle data
134 sent to the server on that socket.
135
136 ### Event: 'upgrade'
137
138 `function (request, socket, head) { }`
139
140 Emitted each time a client requests a http upgrade. If this event isn't
141 listened for, then clients requesting an upgrade will have their connections
142 closed.
143
144 * `request` is the arguments for the http request, as it is in the request
145   event.
146 * `socket` is the network socket between the server and client.
147 * `head` is an instance of Buffer, the first packet of the upgraded stream,
148   this may be empty.
149
150 After this event is emitted, the request's socket will not have a `data`
151 event listener, meaning you will need to bind to it in order to handle data
152 sent to the server on that socket.
153
154 ### Event: 'clientError'
155
156 `function (exception, socket) { }`
157
158 If a client connection emits an 'error' event - it will forwarded here.
159
160 `socket` is the `net.Socket` object that the error originated from.
161
162
163 ### server.listen(port[, hostname]\[, backlog]\[, callback])
164
165 Begin accepting connections on the specified port and hostname.  If the
166 hostname is omitted, the server will accept connections directed to any
167 IPv4 address (`INADDR_ANY`).
168
169 To listen to a unix socket, supply a filename instead of port and hostname.
170
171 Backlog is the maximum length of the queue of pending connections.
172 The actual length will be determined by your OS through sysctl settings such as
173 `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
174 parameter is 511 (not 512).
175
176 This function is asynchronous. The last parameter `callback` will be added as
177 a listener for the ['listening'][] event.  See also [net.Server.listen(port)][].
178
179
180 ### server.listen(path[, callback])
181
182 Start a UNIX socket server listening for connections on the given `path`.
183
184 This function is asynchronous. The last parameter `callback` will be added as
185 a listener for the ['listening'][] event.  See also [net.Server.listen(path)][].
186
187
188 ### server.listen(handle[, callback])
189
190 * `handle` {Object}
191 * `callback` {Function}
192
193 The `handle` object can be set to either a server or socket (anything
194 with an underlying `_handle` member), or a `{fd: <n>}` object.
195
196 This will cause the server to accept connections on the specified
197 handle, but it is presumed that the file descriptor or handle has
198 already been bound to a port or domain socket.
199
200 Listening on a file descriptor is not supported on Windows.
201
202 This function is asynchronous. The last parameter `callback` will be added as
203 a listener for the ['listening'](net.html#event_listening_) event.
204 See also [net.Server.listen()](net.html#net_server_listen_handle_callback).
205
206 ### server.close([callback])
207
208 Stops the server from accepting new connections.  See [net.Server.close()][].
209
210
211 ### server.maxHeadersCount
212
213 Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
214 no limit will be applied.
215
216 ### server.setTimeout(msecs, callback)
217
218 * `msecs` {Number}
219 * `callback` {Function}
220
221 Sets the timeout value for sockets, and emits a `'timeout'` event on
222 the Server object, passing the socket as an argument, if a timeout
223 occurs.
224
225 If there is a `'timeout'` event listener on the Server object, then it
226 will be called with the timed-out socket as an argument.
227
228 By default, the Server's timeout value is 2 minutes, and sockets are
229 destroyed automatically if they time out.  However, if you assign a
230 callback to the Server's `'timeout'` event, then you are responsible
231 for handling socket timeouts.
232
233 ### server.timeout
234
235 * {Number} Default = 120000 (2 minutes)
236
237 The number of milliseconds of inactivity before a socket is presumed
238 to have timed out.
239
240 Note that the socket timeout logic is set up on connection, so
241 changing this value only affects *new* connections to the server, not
242 any existing connections.
243
244 Set to 0 to disable any kind of automatic timeout behavior on incoming
245 connections.
246
247 ## Class: http.ServerResponse
248
249 This object is created internally by a HTTP server--not by the user. It is
250 passed as the second parameter to the `'request'` event.
251
252 The response implements the [Writable Stream][] interface. This is an
253 [EventEmitter][] with the following events:
254
255 ### Event: 'close'
256
257 `function () { }`
258
259 Indicates that the underlying connection was terminated before
260 [response.end()][] was called or able to flush.
261
262 ### Event: 'finish'
263
264 `function () { }`
265
266 Emitted when the response has been sent. More specifically, this event is
267 emitted when the last segment of the response headers and body have been
268 handed off to the operating system for transmission over the network. It
269 does not imply that the client has received anything yet.
270
271 After this event, no more events will be emitted on the response object.
272
273 ### response.writeContinue()
274
275 Sends a HTTP/1.1 100 Continue message to the client, indicating that
276 the request body should be sent. See the ['checkContinue'][] event on `Server`.
277
278 ### response.writeHead(statusCode[, statusMessage]\[, headers])
279
280 Sends a response header to the request. The status code is a 3-digit HTTP
281 status code, like `404`. The last argument, `headers`, are the response headers.
282 Optionally one can give a human-readable `statusMessage` as the second
283 argument.
284
285 Example:
286
287     var body = 'hello world';
288     response.writeHead(200, {
289       'Content-Length': body.length,
290       'Content-Type': 'text/plain' });
291
292 This method must only be called once on a message and it must
293 be called before [response.end()][] is called.
294
295 If you call [response.write()][] or [response.end()][] before calling this, the
296 implicit/mutable headers will be calculated and call this function for you.
297
298 Note: that Content-Length is given in bytes not characters. The above example
299 works because the string `'hello world'` contains only single byte characters.
300 If the body contains higher coded characters then `Buffer.byteLength()`
301 should be used to determine the number of bytes in a given encoding.
302 And Node does not check whether Content-Length and the length of the body
303 which has been transmitted are equal or not.
304
305 ### response.setTimeout(msecs, callback)
306
307 * `msecs` {Number}
308 * `callback` {Function}
309
310 Sets the Socket's timeout value to `msecs`.  If a callback is
311 provided, then it is added as a listener on the `'timeout'` event on
312 the response object.
313
314 If no `'timeout'` listener is added to the request, the response, or
315 the server, then sockets are destroyed when they time out.  If you
316 assign a handler on the request, the response, or the server's
317 `'timeout'` events, then it is your responsibility to handle timed out
318 sockets.
319
320 ### response.statusCode
321
322 When using implicit headers (not calling [response.writeHead()][] explicitly),
323 this property controls the status code that will be sent to the client when
324 the headers get flushed.
325
326 Example:
327
328     response.statusCode = 404;
329
330 After response header was sent to the client, this property indicates the
331 status code which was sent out.
332
333 ### response.statusMessage
334
335 When using implicit headers (not calling `response.writeHead()` explicitly), this property
336 controls the status message that will be sent to the client when the headers get
337 flushed. If this is left as `undefined` then the standard message for the status
338 code will be used.
339
340 Example:
341
342     response.statusMessage = 'Not found';
343
344 After response header was sent to the client, this property indicates the
345 status message which was sent out.
346
347 ### response.setHeader(name, value)
348
349 Sets a single header value for implicit headers.  If this header already exists
350 in the to-be-sent headers, its value will be replaced.  Use an array of strings
351 here if you need to send multiple headers with the same name.
352
353 Example:
354
355     response.setHeader("Content-Type", "text/html");
356
357 or
358
359     response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
360
361 ### response.headersSent
362
363 Boolean (read-only). True if headers were sent, false otherwise.
364
365 ### response.sendDate
366
367 When true, the Date header will be automatically generated and sent in
368 the response if it is not already present in the headers. Defaults to true.
369
370 This should only be disabled for testing; HTTP requires the Date header
371 in responses.
372
373 ### response.getHeader(name)
374
375 Reads out a header that's already been queued but not sent to the client.  Note
376 that the name is case insensitive.  This can only be called before headers get
377 implicitly flushed.
378
379 Example:
380
381     var contentType = response.getHeader('content-type');
382
383 ### response.removeHeader(name)
384
385 Removes a header that's queued for implicit sending.
386
387 Example:
388
389     response.removeHeader("Content-Encoding");
390
391
392 ### response.write(chunk[, encoding])
393
394 If this method is called and [response.writeHead()][] has not been called,
395 it will switch to implicit header mode and flush the implicit headers.
396
397 This sends a chunk of the response body. This method may
398 be called multiple times to provide successive parts of the body.
399
400 `chunk` can be a string or a buffer. If `chunk` is a string,
401 the second parameter specifies how to encode it into a byte stream.
402 By default the `encoding` is `'utf8'`.
403
404 **Note**: This is the raw HTTP body and has nothing to do with
405 higher-level multi-part body encodings that may be used.
406
407 The first time `response.write()` is called, it will send the buffered
408 header information and the first body to the client. The second time
409 `response.write()` is called, Node assumes you're going to be streaming
410 data, and sends that separately. That is, the response is buffered up to the
411 first chunk of body.
412
413 Returns `true` if the entire data was flushed successfully to the kernel
414 buffer. Returns `false` if all or part of the data was queued in user memory.
415 `'drain'` will be emitted when the buffer is again free.
416
417 ### response.addTrailers(headers)
418
419 This method adds HTTP trailing headers (a header but at the end of the
420 message) to the response.
421
422 Trailers will **only** be emitted if chunked encoding is used for the
423 response; if it is not (e.g., if the request was HTTP/1.0), they will
424 be silently discarded.
425
426 Note that HTTP requires the `Trailer` header to be sent if you intend to
427 emit trailers, with a list of the header fields in its value. E.g.,
428
429     response.writeHead(200, { 'Content-Type': 'text/plain',
430                               'Trailer': 'Content-MD5' });
431     response.write(fileData);
432     response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
433     response.end();
434
435
436 ### response.end([data]\[, encoding])
437
438 This method signals to the server that all of the response headers and body
439 have been sent; that server should consider this message complete.
440 The method, `response.end()`, MUST be called on each
441 response.
442
443 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
444 followed by `response.end()`.
445
446
447 ## http.request(options[, callback])
448
449 Node maintains several connections per server to make HTTP requests.
450 This function allows one to transparently issue requests.
451
452 `options` can be an object or a string. If `options` is a string, it is
453 automatically parsed with [url.parse()][].
454
455 Options:
456
457 - `host`: A domain name or IP address of the server to issue the request to.
458   Defaults to `'localhost'`.
459 - `hostname`: To support `url.parse()` `hostname` is preferred over `host`
460 - `port`: Port of remote server. Defaults to 80.
461 - `localAddress`: Local interface to bind for network connections.
462 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
463 - `method`: A string specifying the HTTP request method. Defaults to `'GET'`.
464 - `path`: Request path. Defaults to `'/'`. Should include query string if any.
465   E.G. `'/index.html?page=12'`. An exception is thrown when the request path
466   contains illegal characters. Currently, only spaces are rejected but that
467   may change in the future.
468 - `headers`: An object containing request headers.
469 - `auth`: Basic authentication i.e. `'user:password'` to compute an
470   Authorization header.
471 - `agent`: Controls [Agent][] behavior. When an Agent is used request will
472   default to `Connection: keep-alive`. Possible values:
473  - `undefined` (default): use [global Agent][] for this host and port.
474  - `Agent` object: explicitly use the passed in `Agent`.
475  - `false`: opts out of connection pooling with an Agent, defaults request to
476    `Connection: close`.
477 - `keepAlive`: {Boolean} Keep sockets around in a pool to be used
478   by other requests in the future. Default = `false`
479 - `keepAliveMsecs`: {Integer} When using HTTP KeepAlive, how often to
480   send TCP KeepAlive packets over sockets being kept alive.  Default =
481   `1000`.  Only relevant if `keepAlive` is set to `true`.
482
483 The optional `callback` parameter will be added as a one time listener for
484 the ['response'][] event.
485
486 `http.request()` returns an instance of the [http.ClientRequest][]
487 class. The `ClientRequest` instance is a writable stream. If one needs to
488 upload a file with a POST request, then write to the `ClientRequest` object.
489
490 Example:
491
492     var postData = querystring.stringify({
493       'msg' : 'Hello World!'
494     });
495
496     var options = {
497       hostname: 'www.google.com',
498       port: 80,
499       path: '/upload',
500       method: 'POST',
501       headers: {
502         'Content-Type': 'application/x-www-form-urlencoded',
503         'Content-Length': postData.length
504       }
505     };
506
507     var req = http.request(options, function(res) {
508       console.log('STATUS: ' + res.statusCode);
509       console.log('HEADERS: ' + JSON.stringify(res.headers));
510       res.setEncoding('utf8');
511       res.on('data', function (chunk) {
512         console.log('BODY: ' + chunk);
513       });
514     });
515
516     req.on('error', function(e) {
517       console.log('problem with request: ' + e.message);
518     });
519
520     // write data to request body
521     req.write(postData);
522     req.end();
523
524 Note that in the example `req.end()` was called. With `http.request()` one
525 must always call `req.end()` to signify that you're done with the request -
526 even if there is no data being written to the request body.
527
528 If any error is encountered during the request (be that with DNS resolution,
529 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
530 on the returned request object.
531
532 There are a few special headers that should be noted.
533
534 * Sending a 'Connection: keep-alive' will notify Node that the connection to
535   the server should be persisted until the next request.
536
537 * Sending a 'Content-length' header will disable the default chunked encoding.
538
539 * Sending an 'Expect' header will immediately send the request headers.
540   Usually, when sending 'Expect: 100-continue', you should both set a timeout
541   and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
542   information.
543
544 * Sending an Authorization header will override using the `auth` option
545   to compute basic authentication.
546
547 ## http.get(options[, callback])
548
549 Since most requests are GET requests without bodies, Node provides this
550 convenience method. The only difference between this method and `http.request()`
551 is that it sets the method to GET and calls `req.end()` automatically.
552
553 Example:
554
555     http.get("http://www.google.com/index.html", function(res) {
556       console.log("Got response: " + res.statusCode);
557     }).on('error', function(e) {
558       console.log("Got error: " + e.message);
559     });
560
561
562 ## Class: http.Agent
563
564 The HTTP Agent is used for pooling sockets used in HTTP client
565 requests.
566
567 The HTTP Agent also defaults client requests to using
568 Connection:keep-alive. If no pending HTTP requests are waiting on a
569 socket to become free the socket is closed. This means that Node's
570 pool has the benefit of keep-alive when under load but still does not
571 require developers to manually close the HTTP clients using
572 KeepAlive.
573
574 If you opt into using HTTP KeepAlive, you can create an Agent object
575 with that flag set to `true`.  (See the [constructor
576 options](#http_new_agent_options) below.)  Then, the Agent will keep
577 unused sockets in a pool for later use.  They will be explicitly
578 marked so as to not keep the Node process running.  However, it is
579 still a good idea to explicitly [`destroy()`](#http_agent_destroy)
580 KeepAlive agents when they are no longer in use, so that the Sockets
581 will be shut down.
582
583 Sockets are removed from the agent's pool when the socket emits either
584 a "close" event or a special "agentRemove" event. This means that if
585 you intend to keep one HTTP request open for a long time and don't
586 want it to stay in the pool you can do something along the lines of:
587
588     http.get(options, function(res) {
589       // Do stuff
590     }).on("socket", function (socket) {
591       socket.emit("agentRemove");
592     });
593
594 Alternatively, you could just opt out of pooling entirely using
595 `agent:false`:
596
597     http.get({
598       hostname: 'localhost',
599       port: 80,
600       path: '/',
601       agent: false  // create a new agent just for this one request
602     }, function (res) {
603       // Do stuff with response
604     })
605
606 ### new Agent([options])
607
608 * `options` {Object} Set of configurable options to set on the agent.
609   Can have the following fields:
610   * `keepAlive` {Boolean} Keep sockets around in a pool to be used by
611     other requests in the future. Default = `false`
612   * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often
613     to send TCP KeepAlive packets over sockets being kept alive.
614     Default = `1000`.  Only relevant if `keepAlive` is set to `true`.
615   * `maxSockets` {Number} Maximum number of sockets to allow per
616     host.  Default = `Infinity`.
617   * `maxFreeSockets` {Number} Maximum number of sockets to leave open
618     in a free state.  Only relevant if `keepAlive` is set to `true`.
619     Default = `256`.
620
621 The default `http.globalAgent` that is used by `http.request` has all
622 of these values set to their respective defaults.
623
624 To configure any of them, you must create your own `Agent` object.
625
626 ```javascript
627 var http = require('http');
628 var keepAliveAgent = new http.Agent({ keepAlive: true });
629 options.agent = keepAliveAgent;
630 http.request(options, onResponseCallback);
631 ```
632
633 ### agent.maxSockets
634
635 By default set to Infinity. Determines how many concurrent sockets the agent
636 can have open per origin. Origin is either a 'host:port' or
637 'host:port:localAddress' combination.
638
639 ### agent.maxFreeSockets
640
641 By default set to 256.  For Agents supporting HTTP KeepAlive, this
642 sets the maximum number of sockets that will be left open in the free
643 state.
644
645 ### agent.sockets
646
647 An object which contains arrays of sockets currently in use by the
648 Agent.  Do not modify.
649
650 ### agent.freeSockets
651
652 An object which contains arrays of sockets currently awaiting use by
653 the Agent when HTTP KeepAlive is used.  Do not modify.
654
655 ### agent.requests
656
657 An object which contains queues of requests that have not yet been assigned to
658 sockets. Do not modify.
659
660 ### agent.destroy()
661
662 Destroy any sockets that are currently in use by the agent.
663
664 It is usually not necessary to do this.  However, if you are using an
665 agent with KeepAlive enabled, then it is best to explicitly shut down
666 the agent when you know that it will no longer be used.  Otherwise,
667 sockets may hang open for quite a long time before the server
668 terminates them.
669
670 ### agent.getName(options)
671
672 Get a unique name for a set of request options, to determine whether a
673 connection can be reused.  In the http agent, this returns
674 `host:port:localAddress`.  In the https agent, the name includes the
675 CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
676 socket reusability.
677
678
679 ## http.globalAgent
680
681 Global instance of Agent which is used as the default for all http client
682 requests.
683
684
685 ## Class: http.ClientRequest
686
687 This object is created internally and returned from `http.request()`.  It
688 represents an _in-progress_ request whose header has already been queued.  The
689 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
690 `removeHeader(name)` API.  The actual header will be sent along with the first
691 data chunk or when closing the connection.
692
693 To get the response, add a listener for `'response'` to the request object.
694 `'response'` will be emitted from the request object when the response
695 headers have been received.  The `'response'` event is executed with one
696 argument which is an instance of [http.IncomingMessage][].
697
698 During the `'response'` event, one can add listeners to the
699 response object; particularly to listen for the `'data'` event.
700
701 If no `'response'` handler is added, then the response will be
702 entirely discarded.  However, if you add a `'response'` event handler,
703 then you **must** consume the data from the response object, either by
704 calling `response.read()` whenever there is a `'readable'` event, or
705 by adding a `'data'` handler, or by calling the `.resume()` method.
706 Until the data is consumed, the `'end'` event will not fire.  Also, until
707 the data is read it will consume memory that can eventually lead to a
708 'process out of memory' error.
709
710 Note: Node does not check whether Content-Length and the length of the body
711 which has been transmitted are equal or not.
712
713 The request implements the [Writable Stream][] interface. This is an
714 [EventEmitter][] with the following events:
715
716 ### Event: 'response'
717
718 `function (response) { }`
719
720 Emitted when a response is received to this request. This event is emitted only
721 once. The `response` argument will be an instance of [http.IncomingMessage][].
722
723 Options:
724
725 - `host`: A domain name or IP address of the server to issue the request to.
726 - `port`: Port of remote server.
727 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
728
729 ### Event: 'socket'
730
731 `function (socket) { }`
732
733 Emitted after a socket is assigned to this request.
734
735 ### Event: 'connect'
736
737 `function (response, socket, head) { }`
738
739 Emitted each time a server responds to a request with a CONNECT method. If this
740 event isn't being listened for, clients receiving a CONNECT method will have
741 their connections closed.
742
743 A client server pair that show you how to listen for the `connect` event.
744
745     var http = require('http');
746     var net = require('net');
747     var url = require('url');
748
749     // Create an HTTP tunneling proxy
750     var proxy = http.createServer(function (req, res) {
751       res.writeHead(200, {'Content-Type': 'text/plain'});
752       res.end('okay');
753     });
754     proxy.on('connect', function(req, cltSocket, head) {
755       // connect to an origin server
756       var srvUrl = url.parse('http://' + req.url);
757       var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
758         cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
759                         'Proxy-agent: Node-Proxy\r\n' +
760                         '\r\n');
761         srvSocket.write(head);
762         srvSocket.pipe(cltSocket);
763         cltSocket.pipe(srvSocket);
764       });
765     });
766
767     // now that proxy is running
768     proxy.listen(1337, '127.0.0.1', function() {
769
770       // make a request to a tunneling proxy
771       var options = {
772         port: 1337,
773         hostname: '127.0.0.1',
774         method: 'CONNECT',
775         path: 'www.google.com:80'
776       };
777
778       var req = http.request(options);
779       req.end();
780
781       req.on('connect', function(res, socket, head) {
782         console.log('got connected!');
783
784         // make a request over an HTTP tunnel
785         socket.write('GET / HTTP/1.1\r\n' +
786                      'Host: www.google.com:80\r\n' +
787                      'Connection: close\r\n' +
788                      '\r\n');
789         socket.on('data', function(chunk) {
790           console.log(chunk.toString());
791         });
792         socket.on('end', function() {
793           proxy.close();
794         });
795       });
796     });
797
798 ### Event: 'upgrade'
799
800 `function (response, socket, head) { }`
801
802 Emitted each time a server responds to a request with an upgrade. If this
803 event isn't being listened for, clients receiving an upgrade header will have
804 their connections closed.
805
806 A client server pair that show you how to listen for the `upgrade` event.
807
808     var http = require('http');
809
810     // Create an HTTP server
811     var srv = http.createServer(function (req, res) {
812       res.writeHead(200, {'Content-Type': 'text/plain'});
813       res.end('okay');
814     });
815     srv.on('upgrade', function(req, socket, head) {
816       socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
817                    'Upgrade: WebSocket\r\n' +
818                    'Connection: Upgrade\r\n' +
819                    '\r\n');
820
821       socket.pipe(socket); // echo back
822     });
823
824     // now that server is running
825     srv.listen(1337, '127.0.0.1', function() {
826
827       // make a request
828       var options = {
829         port: 1337,
830         hostname: '127.0.0.1',
831         headers: {
832           'Connection': 'Upgrade',
833           'Upgrade': 'websocket'
834         }
835       };
836
837       var req = http.request(options);
838       req.end();
839
840       req.on('upgrade', function(res, socket, upgradeHead) {
841         console.log('got upgraded!');
842         socket.end();
843         process.exit(0);
844       });
845     });
846
847 ### Event: 'continue'
848
849 `function () { }`
850
851 Emitted when the server sends a '100 Continue' HTTP response, usually because
852 the request contained 'Expect: 100-continue'. This is an instruction that
853 the client should send the request body.
854
855 ### request.flush()
856
857 Flush the request headers.
858
859 For efficiency reasons, node.js normally buffers the request headers until you
860 call `request.end()` or write the first chunk of request data.  It then tries
861 hard to pack the request headers and data into a single TCP packet.
862
863 That's usually what you want (it saves a TCP round-trip) but not when the first
864 data isn't sent until possibly much later.  `request.flush()` lets you bypass
865 the optimization and kickstart the request.
866
867 ### request.write(chunk[, encoding])
868
869 Sends a chunk of the body.  By calling this method
870 many times, the user can stream a request body to a
871 server--in that case it is suggested to use the
872 `['Transfer-Encoding', 'chunked']` header line when
873 creating the request.
874
875 The `chunk` argument should be a [Buffer][] or a string.
876
877 The `encoding` argument is optional and only applies when `chunk` is a string.
878 Defaults to `'utf8'`.
879
880
881 ### request.end([data]\[, encoding])
882
883 Finishes sending the request. If any parts of the body are
884 unsent, it will flush them to the stream. If the request is
885 chunked, this will send the terminating `'0\r\n\r\n'`.
886
887 If `data` is specified, it is equivalent to calling
888 `request.write(data, encoding)` followed by `request.end()`.
889
890 ### request.abort()
891
892 Aborts a request.  (New since v0.3.8.)
893
894 ### request.setTimeout(timeout[, callback])
895
896 Once a socket is assigned to this request and is connected
897 [socket.setTimeout()][] will be called.
898
899 ### request.setNoDelay([noDelay])
900
901 Once a socket is assigned to this request and is connected
902 [socket.setNoDelay()][] will be called.
903
904 ### request.setSocketKeepAlive([enable]\[, initialDelay])
905
906 Once a socket is assigned to this request and is connected
907 [socket.setKeepAlive()][] will be called.
908
909
910 ## http.IncomingMessage
911
912 An `IncomingMessage` object is created by [http.Server][] or
913 [http.ClientRequest][] and passed as the first argument to the `'request'`
914 and `'response'` event respectively. It may be used to access response status,
915 headers and data.
916
917 It implements the [Readable Stream][] interface, as well as the
918 following additional events, methods, and properties.
919
920 ### Event: 'close'
921
922 `function () { }`
923
924 Indicates that the underlaying connection was closed.
925 Just like `'end'`, this event occurs only once per response.
926
927 ### message.httpVersion
928
929 In case of server request, the HTTP version sent by the client. In the case of
930 client response, the HTTP version of the connected-to server.
931 Probably either `'1.1'` or `'1.0'`.
932
933 Also `response.httpVersionMajor` is the first integer and
934 `response.httpVersionMinor` is the second.
935
936 ### message.headers
937
938 The request/response headers object.
939
940 Read only map of header names and values. Header names are lower-cased.
941 Example:
942
943     // Prints something like:
944     //
945     // { 'user-agent': 'curl/7.22.0',
946     //   host: '127.0.0.1:8000',
947     //   accept: '*/*' }
948     console.log(request.headers);
949
950 ### message.rawHeaders
951
952 The raw request/response headers list exactly as they were received.
953
954 Note that the keys and values are in the same list.  It is *not* a
955 list of tuples.  So, the even-numbered offsets are key values, and the
956 odd-numbered offsets are the associated values.
957
958 Header names are not lowercased, and duplicates are not merged.
959
960     // Prints something like:
961     //
962     // [ 'user-agent',
963     //   'this is invalid because there can be only one',
964     //   'User-Agent',
965     //   'curl/7.22.0',
966     //   'Host',
967     //   '127.0.0.1:8000',
968     //   'ACCEPT',
969     //   '*/*' ]
970     console.log(request.rawHeaders);
971
972 ### message.trailers
973
974 The request/response trailers object. Only populated at the 'end' event.
975
976 ### message.rawTrailers
977
978 The raw request/response trailer keys and values exactly as they were
979 received.  Only populated at the 'end' event.
980
981 ### message.setTimeout(msecs, callback)
982
983 * `msecs` {Number}
984 * `callback` {Function}
985
986 Calls `message.connection.setTimeout(msecs, callback)`.
987
988 ### message.method
989
990 **Only valid for request obtained from [http.Server][].**
991
992 The request method as a string. Read only. Example:
993 `'GET'`, `'DELETE'`.
994
995 ### message.url
996
997 **Only valid for request obtained from [http.Server][].**
998
999 Request URL string. This contains only the URL that is
1000 present in the actual HTTP request. If the request is:
1001
1002     GET /status?name=ryan HTTP/1.1\r\n
1003     Accept: text/plain\r\n
1004     \r\n
1005
1006 Then `request.url` will be:
1007
1008     '/status?name=ryan'
1009
1010 If you would like to parse the URL into its parts, you can use
1011 `require('url').parse(request.url)`.  Example:
1012
1013     node> require('url').parse('/status?name=ryan')
1014     { href: '/status?name=ryan',
1015       search: '?name=ryan',
1016       query: 'name=ryan',
1017       pathname: '/status' }
1018
1019 If you would like to extract the params from the query string,
1020 you can use the `require('querystring').parse` function, or pass
1021 `true` as the second argument to `require('url').parse`.  Example:
1022
1023     node> require('url').parse('/status?name=ryan', true)
1024     { href: '/status?name=ryan',
1025       search: '?name=ryan',
1026       query: { name: 'ryan' },
1027       pathname: '/status' }
1028
1029 ### message.statusCode
1030
1031 **Only valid for response obtained from `http.ClientRequest`.**
1032
1033 The 3-digit HTTP response status code. E.G. `404`.
1034
1035 ### message.statusMessage
1036
1037 **Only valid for response obtained from `http.ClientRequest`.**
1038
1039 The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
1040
1041 ### message.socket
1042
1043 The `net.Socket` object associated with the connection.
1044
1045 With HTTPS support, use request.connection.verifyPeer() and
1046 request.connection.getPeerCertificate() to obtain the client's
1047 authentication details.
1048
1049
1050 ['checkContinue']: #http_event_checkcontinue
1051 ['listening']: net.html#net_event_listening
1052 ['response']: #http_event_response
1053 [Agent]: #http_class_http_agent
1054 [Buffer]: buffer.html#buffer_buffer
1055 [EventEmitter]: events.html#events_class_events_eventemitter
1056 [Readable Stream]: stream.html#stream_class_stream_readable
1057 [Writable Stream]: stream.html#stream_class_stream_writable
1058 [global Agent]: #http_http_globalagent
1059 [http.ClientRequest]: #http_class_http_clientrequest
1060 [http.IncomingMessage]: #http_http_incomingmessage
1061 [http.ServerResponse]: #http_class_http_serverresponse
1062 [http.Server]: #http_class_http_server
1063 [http.request()]: #http_http_request_options_callback
1064 [http.request()]: #http_http_request_options_callback
1065 [net.Server.close()]: net.html#net_server_close_callback
1066 [net.Server.listen(path)]: net.html#net_server_listen_path_callback
1067 [net.Server.listen(port)]: net.html#net_server_listen_port_host_backlog_callback
1068 [response.end()]: #http_response_end_data_encoding
1069 [response.write()]: #http_response_write_chunk_encoding
1070 [response.writeContinue()]: #http_response_writecontinue
1071 [response.writeHead()]: #http_response_writehead_statuscode_reasonphrase_headers
1072 [socket.setKeepAlive()]: net.html#net_socket_setkeepalive_enable_initialdelay
1073 [socket.setNoDelay()]: net.html#net_socket_setnodelay_nodelay
1074 [socket.setTimeout()]: net.html#net_socket_settimeout_timeout_callback
1075 [stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding
1076 [url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost