5 To use the HTTP server and client one must `require('http')`.
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.
13 HTTP message headers are represented by an object like this:
15 { 'content-length': '123',
16 'content-type': 'text/plain',
17 'connection': 'keep-alive',
21 Keys are lowercased. Values are not modified.
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.
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.
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:
39 [ 'ConTent-Length', '123456',
40 'content-LENGTH', '123',
41 'content-type', 'text/plain',
42 'CONNECTION', 'keep-alive',
50 A list of the HTTP methods that are supported by the parser.
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
60 ## http.createServer([requestListener])
62 Returns a new web server object.
64 The `requestListener` is a function which is automatically
65 added to the `'request'` event.
67 ## http.createClient([port]\[, host])
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
75 This is an [EventEmitter][] with the following events:
79 `function (request, response) { }`
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][].
86 ### Event: 'connection'
88 `function (socket) { }`
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`.
100 Emitted when the server closes.
102 ### Event: 'checkContinue'
104 `function (request, response) { }`
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.
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
115 Note that when this event is emitted and handled, the `request` event will
120 `function (request, socket, head) { }`
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
126 * `request` is the arguments for the http request, as it is in the request
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,
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.
138 `function (request, socket, head) { }`
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
144 * `request` is the arguments for the http request, as it is in the request
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,
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.
154 ### Event: 'clientError'
156 `function (exception, socket) { }`
158 If a client connection emits an 'error' event - it will forwarded here.
160 `socket` is the `net.Socket` object that the error originated from.
163 ### server.listen(port[, hostname]\[, backlog]\[, callback])
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`).
169 To listen to a unix socket, supply a filename instead of port and hostname.
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).
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)][].
180 ### server.listen(path[, callback])
182 Start a UNIX socket server listening for connections on the given `path`.
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)][].
188 ### server.listen(handle[, callback])
191 * `callback` {Function}
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.
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.
200 Listening on a file descriptor is not supported on Windows.
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).
206 ### server.close([callback])
208 Stops the server from accepting new connections. See [net.Server.close()][].
211 ### server.maxHeadersCount
213 Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
214 no limit will be applied.
216 ### server.setTimeout(msecs, callback)
219 * `callback` {Function}
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
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.
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.
235 * {Number} Default = 120000 (2 minutes)
237 The number of milliseconds of inactivity before a socket is presumed
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.
244 Set to 0 to disable any kind of automatic timeout behavior on incoming
247 ## Class: http.ServerResponse
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.
252 The response implements the [Writable Stream][] interface. This is an
253 [EventEmitter][] with the following events:
259 Indicates that the underlying connection was terminated before
260 [response.end()][] was called or able to flush.
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.
271 After this event, no more events will be emitted on the response object.
273 ### response.writeContinue()
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`.
278 ### response.writeHead(statusCode[, statusMessage]\[, headers])
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
287 var body = 'hello world';
288 response.writeHead(200, {
289 'Content-Length': body.length,
290 'Content-Type': 'text/plain' });
292 This method must only be called once on a message and it must
293 be called before [response.end()][] is called.
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.
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.
305 ### response.setTimeout(msecs, callback)
308 * `callback` {Function}
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
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
320 ### response.statusCode
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.
328 response.statusCode = 404;
330 After response header was sent to the client, this property indicates the
331 status code which was sent out.
333 ### response.statusMessage
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
342 response.statusMessage = 'Not found';
344 After response header was sent to the client, this property indicates the
345 status message which was sent out.
347 ### response.setHeader(name, value)
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.
355 response.setHeader("Content-Type", "text/html");
359 response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
361 ### response.headersSent
363 Boolean (read-only). True if headers were sent, false otherwise.
365 ### response.sendDate
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.
370 This should only be disabled for testing; HTTP requires the Date header
373 ### response.getHeader(name)
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
381 var contentType = response.getHeader('content-type');
383 ### response.removeHeader(name)
385 Removes a header that's queued for implicit sending.
389 response.removeHeader("Content-Encoding");
392 ### response.write(chunk[, encoding])
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.
397 This sends a chunk of the response body. This method may
398 be called multiple times to provide successive parts of the body.
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'`.
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.
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
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.
417 ### response.addTrailers(headers)
419 This method adds HTTP trailing headers (a header but at the end of the
420 message) to the response.
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.
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.,
429 response.writeHead(200, { 'Content-Type': 'text/plain',
430 'Trailer': 'Content-MD5' });
431 response.write(fileData);
432 response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
436 ### response.end([data]\[, encoding])
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
443 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
444 followed by `response.end()`.
447 ## http.request(options[, callback])
449 Node maintains several connections per server to make HTTP requests.
450 This function allows one to transparently issue requests.
452 `options` can be an object or a string. If `options` is a string, it is
453 automatically parsed with [url.parse()][].
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
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`.
483 The optional `callback` parameter will be added as a one time listener for
484 the ['response'][] event.
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.
492 var postData = querystring.stringify({
493 'msg' : 'Hello World!'
497 hostname: 'www.google.com',
502 'Content-Type': 'application/x-www-form-urlencoded',
503 'Content-Length': postData.length
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);
516 req.on('error', function(e) {
517 console.log('problem with request: ' + e.message);
520 // write data to request body
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.
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.
532 There are a few special headers that should be noted.
534 * Sending a 'Connection: keep-alive' will notify Node that the connection to
535 the server should be persisted until the next request.
537 * Sending a 'Content-length' header will disable the default chunked encoding.
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
544 * Sending an Authorization header will override using the `auth` option
545 to compute basic authentication.
547 ## http.get(options[, callback])
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.
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);
564 The HTTP Agent is used for pooling sockets used in HTTP client
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
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
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:
588 http.get(options, function(res) {
590 }).on("socket", function (socket) {
591 socket.emit("agentRemove");
594 Alternatively, you could just opt out of pooling entirely using
598 hostname: 'localhost',
601 agent: false // create a new agent just for this one request
603 // Do stuff with response
606 ### new Agent([options])
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`.
621 The default `http.globalAgent` that is used by `http.request` has all
622 of these values set to their respective defaults.
624 To configure any of them, you must create your own `Agent` object.
627 var http = require('http');
628 var keepAliveAgent = new http.Agent({ keepAlive: true });
629 options.agent = keepAliveAgent;
630 http.request(options, onResponseCallback);
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.
639 ### agent.maxFreeSockets
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
647 An object which contains arrays of sockets currently in use by the
648 Agent. Do not modify.
650 ### agent.freeSockets
652 An object which contains arrays of sockets currently awaiting use by
653 the Agent when HTTP KeepAlive is used. Do not modify.
657 An object which contains queues of requests that have not yet been assigned to
658 sockets. Do not modify.
662 Destroy any sockets that are currently in use by the agent.
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
670 ### agent.getName(options)
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
681 Global instance of Agent which is used as the default for all http client
685 ## Class: http.ClientRequest
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.
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][].
698 During the `'response'` event, one can add listeners to the
699 response object; particularly to listen for the `'data'` event.
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.
710 Note: Node does not check whether Content-Length and the length of the body
711 which has been transmitted are equal or not.
713 The request implements the [Writable Stream][] interface. This is an
714 [EventEmitter][] with the following events:
716 ### Event: 'response'
718 `function (response) { }`
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][].
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)
731 `function (socket) { }`
733 Emitted after a socket is assigned to this request.
737 `function (response, socket, head) { }`
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.
743 A client server pair that show you how to listen for the `connect` event.
745 var http = require('http');
746 var net = require('net');
747 var url = require('url');
749 // Create an HTTP tunneling proxy
750 var proxy = http.createServer(function (req, res) {
751 res.writeHead(200, {'Content-Type': 'text/plain'});
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' +
761 srvSocket.write(head);
762 srvSocket.pipe(cltSocket);
763 cltSocket.pipe(srvSocket);
767 // now that proxy is running
768 proxy.listen(1337, '127.0.0.1', function() {
770 // make a request to a tunneling proxy
773 hostname: '127.0.0.1',
775 path: 'www.google.com:80'
778 var req = http.request(options);
781 req.on('connect', function(res, socket, head) {
782 console.log('got connected!');
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' +
789 socket.on('data', function(chunk) {
790 console.log(chunk.toString());
792 socket.on('end', function() {
800 `function (response, socket, head) { }`
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.
806 A client server pair that show you how to listen for the `upgrade` event.
808 var http = require('http');
810 // Create an HTTP server
811 var srv = http.createServer(function (req, res) {
812 res.writeHead(200, {'Content-Type': 'text/plain'});
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' +
821 socket.pipe(socket); // echo back
824 // now that server is running
825 srv.listen(1337, '127.0.0.1', function() {
830 hostname: '127.0.0.1',
832 'Connection': 'Upgrade',
833 'Upgrade': 'websocket'
837 var req = http.request(options);
840 req.on('upgrade', function(res, socket, upgradeHead) {
841 console.log('got upgraded!');
847 ### Event: 'continue'
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.
857 Flush the request headers.
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.
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.
867 ### request.write(chunk[, encoding])
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.
875 The `chunk` argument should be a [Buffer][] or a string.
877 The `encoding` argument is optional and only applies when `chunk` is a string.
878 Defaults to `'utf8'`.
881 ### request.end([data]\[, encoding])
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'`.
887 If `data` is specified, it is equivalent to calling
888 `request.write(data, encoding)` followed by `request.end()`.
892 Aborts a request. (New since v0.3.8.)
894 ### request.setTimeout(timeout[, callback])
896 Once a socket is assigned to this request and is connected
897 [socket.setTimeout()][] will be called.
899 ### request.setNoDelay([noDelay])
901 Once a socket is assigned to this request and is connected
902 [socket.setNoDelay()][] will be called.
904 ### request.setSocketKeepAlive([enable]\[, initialDelay])
906 Once a socket is assigned to this request and is connected
907 [socket.setKeepAlive()][] will be called.
910 ## http.IncomingMessage
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,
917 It implements the [Readable Stream][] interface, as well as the
918 following additional events, methods, and properties.
924 Indicates that the underlaying connection was closed.
925 Just like `'end'`, this event occurs only once per response.
927 ### message.httpVersion
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'`.
933 Also `response.httpVersionMajor` is the first integer and
934 `response.httpVersionMinor` is the second.
938 The request/response headers object.
940 Read only map of header names and values. Header names are lower-cased.
943 // Prints something like:
945 // { 'user-agent': 'curl/7.22.0',
946 // host: '127.0.0.1:8000',
948 console.log(request.headers);
950 ### message.rawHeaders
952 The raw request/response headers list exactly as they were received.
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.
958 Header names are not lowercased, and duplicates are not merged.
960 // Prints something like:
963 // 'this is invalid because there can be only one',
970 console.log(request.rawHeaders);
974 The request/response trailers object. Only populated at the 'end' event.
976 ### message.rawTrailers
978 The raw request/response trailer keys and values exactly as they were
979 received. Only populated at the 'end' event.
981 ### message.setTimeout(msecs, callback)
984 * `callback` {Function}
986 Calls `message.connection.setTimeout(msecs, callback)`.
990 **Only valid for request obtained from [http.Server][].**
992 The request method as a string. Read only. Example:
997 **Only valid for request obtained from [http.Server][].**
999 Request URL string. This contains only the URL that is
1000 present in the actual HTTP request. If the request is:
1002 GET /status?name=ryan HTTP/1.1\r\n
1003 Accept: text/plain\r\n
1006 Then `request.url` will be:
1010 If you would like to parse the URL into its parts, you can use
1011 `require('url').parse(request.url)`. Example:
1013 node> require('url').parse('/status?name=ryan')
1014 { href: '/status?name=ryan',
1015 search: '?name=ryan',
1017 pathname: '/status' }
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:
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' }
1029 ### message.statusCode
1031 **Only valid for response obtained from `http.ClientRequest`.**
1033 The 3-digit HTTP response status code. E.G. `404`.
1035 ### message.statusMessage
1037 **Only valid for response obtained from `http.ClientRequest`.**
1039 The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
1043 The `net.Socket` object associated with the connection.
1045 With HTTPS support, use request.connection.verifyPeer() and
1046 request.connection.getPeerCertificate() to obtain the client's
1047 authentication details.
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