diff --git a/doc/api/http.markdown b/doc/api/http.markdown index 1506ca10a34fbc..2e4775398c68dc 100644 --- a/doc/api/http.markdown +++ b/doc/api/http.markdown @@ -43,906 +43,747 @@ list like the following: 'Host', 'mysite.com', 'accepT', '*/*' ] -## http.METHODS - -* {Array} - -A list of the HTTP methods that are supported by the parser. - -## http.STATUS_CODES - -* {Object} - -A collection of all the standard HTTP response status codes, and the -short description of each. For example, `http.STATUS_CODES[404] === 'Not -Found'`. - -## http.createServer([requestListener]) - -Returns a new instance of [http.Server](#http_class_http_server). - -The `requestListener` is a function which is automatically -added to the `'request'` event. - -## http.createClient([port][, host]) - - Stability: 0 - Deprecated: Use [http.request][] instead. - -Constructs a new HTTP client. `port` and `host` refer to the server to be -connected to. - -## Class: http.Server - -This is an [EventEmitter][] with the following events: - -### Event: 'request' - -`function (request, response) { }` - -Emitted each time there is a request. Note that there may be multiple requests -per connection (in the case of keep-alive connections). - `request` is an instance of [http.IncomingMessage][] and `response` is -an instance of [http.ServerResponse][]. - -### Event: 'connection' - -`function (socket) { }` - -When a new TCP stream is established. `socket` is an object of type -`net.Socket`. Usually users will not want to access this event. In -particular, the socket will not emit `readable` events because of how -the protocol parser attaches to the socket. The `socket` can also be -accessed at `request.connection`. - -### Event: 'close' - -`function () { }` - -Emitted when the server closes. - -### Event: 'checkContinue' - -`function (request, response) { }` - -Emitted each time a request with an http Expect: 100-continue is received. -If this event isn't listened for, the server will automatically respond -with a 100 Continue as appropriate. - -Handling this event involves calling [response.writeContinue()][] if the client -should continue to send the request body, or generating an appropriate HTTP -response (e.g., 400 Bad Request) if the client should not continue to send the -request body. - -Note that when this event is emitted and handled, the `request` event will -not be emitted. - -### Event: 'connect' - -`function (request, socket, head) { }` - -Emitted each time a client requests a http CONNECT method. If this event isn't -listened for, then clients requesting a CONNECT method will have their -connections closed. - -* `request` is the arguments for the http request, as it is in the request - event. -* `socket` is the network socket between the server and client. -* `head` is an instance of Buffer, the first packet of the tunneling stream, - this may be empty. - -After this event is emitted, the request's socket will not have a `data` -event listener, meaning you will need to bind to it in order to handle data -sent to the server on that socket. - -### Event: 'upgrade' - -`function (request, socket, head) { }` - -Emitted each time a client requests a http upgrade. If this event isn't -listened for, then clients requesting an upgrade will have their connections -closed. - -* `request` is the arguments for the http request, as it is in the request - event. -* `socket` is the network socket between the server and client. -* `head` is an instance of Buffer, the first packet of the upgraded stream, - this may be empty. - -After this event is emitted, the request's socket will not have a `data` -event listener, meaning you will need to bind to it in order to handle data -sent to the server on that socket. - -### Event: 'clientError' - -`function (exception, socket) { }` - -If a client connection emits an 'error' event, it will be forwarded here. - -`socket` is the `net.Socket` object that the error originated from. - - -### server.listen(port[, hostname][, backlog][, callback]) +## Class: http.Agent -Begin accepting connections on the specified `port` and `hostname`. If the -`hostname` is omitted, the server will accept connections on any IPv6 address -(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A -port value of zero will assign a random port. +The HTTP Agent is used for pooling sockets used in HTTP client +requests. -To listen to a unix socket, supply a filename instead of port and hostname. +The HTTP Agent also defaults client requests to using +Connection:keep-alive. If no pending HTTP requests are waiting on a +socket to become free the socket is closed. This means that Node.js's +pool has the benefit of keep-alive when under load but still does not +require developers to manually close the HTTP clients using +KeepAlive. -Backlog is the maximum length of the queue of pending connections. -The actual length will be determined by your OS through sysctl settings such as -`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this -parameter is 511 (not 512). +If you opt into using HTTP KeepAlive, you can create an Agent object +with that flag set to `true`. (See the [constructor +options](#http_new_agent_options) below.) Then, the Agent will keep +unused sockets in a pool for later use. They will be explicitly +marked so as to not keep the Node.js process running. However, it is +still a good idea to explicitly [`destroy()`](#http_agent_destroy) +KeepAlive agents when they are no longer in use, so that the Sockets +will be shut down. -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. +Sockets are removed from the agent's pool when the socket emits either +a "close" event or a special "agentRemove" event. This means that if +you intend to keep one HTTP request open for a long time and don't +want it to stay in the pool you can do something along the lines of: + http.get(options, function(res) { + // Do stuff + }).on("socket", function (socket) { + socket.emit("agentRemove"); + }); -### server.listen(path[, callback]) +Alternatively, you could just opt out of pooling entirely using +`agent:false`: -Start a UNIX socket server listening for connections on the given `path`. + http.get({ + hostname: 'localhost', + port: 80, + path: '/', + agent: false // create a new agent just for this one request + }, function (res) { + // Do stuff with response + }) -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. +### new Agent([options]) +* `options` {Object} Set of configurable options to set on the agent. + Can have the following fields: + * `keepAlive` {Boolean} Keep sockets around in a pool to be used by + other requests in the future. Default = `false` + * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often + to send TCP KeepAlive packets over sockets being kept alive. + Default = `1000`. Only relevant if `keepAlive` is set to `true`. + * `maxSockets` {Number} Maximum number of sockets to allow per + host. Default = `Infinity`. + * `maxFreeSockets` {Number} Maximum number of sockets to leave open + in a free state. Only relevant if `keepAlive` is set to `true`. + Default = `256`. -### server.listen(handle[, callback]) +The default `http.globalAgent` that is used by `http.request` has all +of these values set to their respective defaults. -* `handle` {Object} -* `callback` {Function} +To configure any of them, you must create your own `Agent` object. -The `handle` object can be set to either a server or socket (anything -with an underlying `_handle` member), or a `{fd: }` object. +```javascript +var http = require('http'); +var keepAliveAgent = new http.Agent({ keepAlive: true }); +options.agent = keepAliveAgent; +http.request(options, onResponseCallback); +``` -This will cause the server to accept connections on the specified -handle, but it is presumed that the file descriptor or handle has -already been bound to a port or domain socket. +### agent.destroy() -Listening on a file descriptor is not supported on Windows. +Destroy any sockets that are currently in use by the agent. -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'](net.html#net_event_listening) event. -See also [net.Server.listen()](net.html#net_server_listen_handle_callback). +It is usually not necessary to do this. However, if you are using an +agent with KeepAlive enabled, then it is best to explicitly shut down +the agent when you know that it will no longer be used. Otherwise, +sockets may hang open for quite a long time before the server +terminates them. -### server.close([callback]) +### agent.freeSockets -Stops the server from accepting new connections. See [net.Server.close()][]. +An object which contains arrays of sockets currently awaiting use by +the Agent when HTTP KeepAlive is used. Do not modify. +### agent.getName(options) -### server.maxHeadersCount +Get a unique name for a set of request options, to determine whether a +connection can be reused. In the http agent, this returns +`host:port:localAddress`. In the https agent, the name includes the +CA, cert, ciphers, and other HTTPS/TLS-specific options that determine +socket reusability. -Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - -no limit will be applied. +### agent.maxFreeSockets -### server.setTimeout(msecs, callback) +By default set to 256. For Agents supporting HTTP KeepAlive, this +sets the maximum number of sockets that will be left open in the free +state. -* `msecs` {Number} -* `callback` {Function} +### agent.maxSockets -Sets the timeout value for sockets, and emits a `'timeout'` event on -the Server object, passing the socket as an argument, if a timeout -occurs. +By default set to Infinity. Determines how many concurrent sockets the agent +can have open per origin. Origin is either a 'host:port' or +'host:port:localAddress' combination. -If there is a `'timeout'` event listener on the Server object, then it -will be called with the timed-out socket as an argument. +### agent.requests -By default, the Server's timeout value is 2 minutes, and sockets are -destroyed automatically if they time out. However, if you assign a -callback to the Server's `'timeout'` event, then you are responsible -for handling socket timeouts. +An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify. -Returns `server`. +### agent.sockets -### server.timeout +An object which contains arrays of sockets currently in use by the +Agent. Do not modify. -* {Number} Default = 120000 (2 minutes) +## Class: http.ClientRequest -The number of milliseconds of inactivity before a socket is presumed -to have timed out. +This object is created internally and returned from `http.request()`. It +represents an _in-progress_ request whose header has already been queued. The +header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, +`removeHeader(name)` API. The actual header will be sent along with the first +data chunk or when closing the connection. -Note that the socket timeout logic is set up on connection, so -changing this value only affects *new* connections to the server, not -any existing connections. +To get the response, add a listener for `'response'` to the request object. +`'response'` will be emitted from the request object when the response +headers have been received. The `'response'` event is executed with one +argument which is an instance of [http.IncomingMessage][]. -Set to 0 to disable any kind of automatic timeout behavior on incoming -connections. +During the `'response'` event, one can add listeners to the +response object; particularly to listen for the `'data'` event. -## Class: http.ServerResponse +If no `'response'` handler is added, then the response will be +entirely discarded. However, if you add a `'response'` event handler, +then you **must** consume the data from the response object, either by +calling `response.read()` whenever there is a `'readable'` event, or +by adding a `'data'` handler, or by calling the `.resume()` method. +Until the data is consumed, the `'end'` event will not fire. Also, until +the data is read it will consume memory that can eventually lead to a +'process out of memory' error. -This object is created internally by a HTTP server--not by the user. It is -passed as the second parameter to the `'request'` event. +Note: Node.js does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. -The response implements the [Writable Stream][] interface. This is an +The request implements the [Writable Stream][] interface. This is an [EventEmitter][] with the following events: -### Event: 'close' - -`function () { }` - -Indicates that the underlying connection was terminated before -[response.end()][] was called or able to flush. - -### Event: 'finish' +### Event: 'abort' `function () { }` -Emitted when the response has been sent. More specifically, this event is -emitted when the last segment of the response headers and body have been -handed off to the operating system for transmission over the network. It -does not imply that the client has received anything yet. - -After this event, no more events will be emitted on the response object. - -### response.writeContinue() - -Sends a HTTP/1.1 100 Continue message to the client, indicating that -the request body should be sent. See the ['checkContinue'][] event on `Server`. - -### response.writeHead(statusCode[, statusMessage][, headers]) - -Sends a response header to the request. The status code is a 3-digit HTTP -status code, like `404`. The last argument, `headers`, are the response headers. -Optionally one can give a human-readable `statusMessage` as the second -argument. - -Example: +Emitted when the request has been aborted by the client. This event is only +emitted on the first call to `abort()`. - var body = 'hello world'; - response.writeHead(200, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' }); +### Event: 'connect' -This method must only be called once on a message and it must -be called before [response.end()][] is called. +`function (response, socket, head) { }` -If you call [response.write()][] or [response.end()][] before calling this, the -implicit/mutable headers will be calculated and call this function for you. +Emitted each time a server responds to a request with a CONNECT method. If this +event isn't being listened for, clients receiving a CONNECT method will have +their connections closed. -Note that Content-Length is given in bytes not characters. The above example -works because the string `'hello world'` contains only single byte characters. -If the body contains higher coded characters then `Buffer.byteLength()` -should be used to determine the number of bytes in a given encoding. -And Node.js does not check whether Content-Length and the length of the body -which has been transmitted are equal or not. +A client server pair that show you how to listen for the `connect` event. -### response.setTimeout(msecs, callback) + var http = require('http'); + var net = require('net'); + var url = require('url'); -* `msecs` {Number} -* `callback` {Function} + // Create an HTTP tunneling proxy + var proxy = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + proxy.on('connect', function(req, cltSocket, head) { + // connect to an origin server + var srvUrl = url.parse('http://' + req.url); + var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { + cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + + 'Proxy-agent: Node.js-Proxy\r\n' + + '\r\n'); + srvSocket.write(head); + srvSocket.pipe(cltSocket); + cltSocket.pipe(srvSocket); + }); + }); -Sets the Socket's timeout value to `msecs`. If a callback is -provided, then it is added as a listener on the `'timeout'` event on -the response object. + // now that proxy is running + proxy.listen(1337, '127.0.0.1', function() { -If no `'timeout'` listener is added to the request, the response, or -the server, then sockets are destroyed when they time out. If you -assign a handler on the request, the response, or the server's -`'timeout'` events, then it is your responsibility to handle timed out -sockets. + // make a request to a tunneling proxy + var options = { + port: 1337, + hostname: '127.0.0.1', + method: 'CONNECT', + path: 'www.google.com:80' + }; -Returns `response`. + var req = http.request(options); + req.end(); -### response.statusCode + req.on('connect', function(res, socket, head) { + console.log('got connected!'); -When using implicit headers (not calling [response.writeHead()][] explicitly), -this property controls the status code that will be sent to the client when -the headers get flushed. + // make a request over an HTTP tunnel + socket.write('GET / HTTP/1.1\r\n' + + 'Host: www.google.com:80\r\n' + + 'Connection: close\r\n' + + '\r\n'); + socket.on('data', function(chunk) { + console.log(chunk.toString()); + }); + socket.on('end', function() { + proxy.close(); + }); + }); + }); -Example: +### Event: 'continue' - response.statusCode = 404; +`function () { }` -After response header was sent to the client, this property indicates the -status code which was sent out. +Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body. -### response.statusMessage +### Event: 'response' -When using implicit headers (not calling `response.writeHead()` explicitly), this property -controls the status message that will be sent to the client when the headers get -flushed. If this is left as `undefined` then the standard message for the status -code will be used. +`function (response) { }` -Example: +Emitted when a response is received to this request. This event is emitted only +once. The `response` argument will be an instance of [http.IncomingMessage][]. - response.statusMessage = 'Not found'; +Options: -After response header was sent to the client, this property indicates the -status message which was sent out. +- `host`: A domain name or IP address of the server to issue the request to. +- `port`: Port of remote server. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) -### response.setHeader(name, value) +### Event: 'socket' -Sets a single header value for implicit headers. If this header already exists -in the to-be-sent headers, its value will be replaced. Use an array of strings -here if you need to send multiple headers with the same name. +`function (socket) { }` -Example: +Emitted after a socket is assigned to this request. - response.setHeader("Content-Type", "text/html"); +### Event: 'upgrade' -or +`function (response, socket, head) { }` - response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); +Emitted each time a server responds to a request with an upgrade. If this +event isn't being listened for, clients receiving an upgrade header will have +their connections closed. -### response.headersSent +A client server pair that show you how to listen for the `upgrade` event. -Boolean (read-only). True if headers were sent, false otherwise. + var http = require('http'); -### response.sendDate + // Create an HTTP server + var srv = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + srv.on('upgrade', function(req, socket, head) { + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n'); -When true, the Date header will be automatically generated and sent in -the response if it is not already present in the headers. Defaults to true. + socket.pipe(socket); // echo back + }); -This should only be disabled for testing; HTTP requires the Date header -in responses. + // now that server is running + srv.listen(1337, '127.0.0.1', function() { -### response.getHeader(name) + // make a request + var options = { + port: 1337, + hostname: '127.0.0.1', + headers: { + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; -Reads out a header that's already been queued but not sent to the client. Note -that the name is case insensitive. This can only be called before headers get -implicitly flushed. + var req = http.request(options); + req.end(); -Example: + req.on('upgrade', function(res, socket, upgradeHead) { + console.log('got upgraded!'); + socket.end(); + process.exit(0); + }); + }); - var contentType = response.getHeader('content-type'); +### request.abort() -### response.removeHeader(name) +Marks the request as aborting. Calling this will cause remaining data +in the response to be dropped and the socket to be destroyed. -Removes a header that's queued for implicit sending. +### request.end([data][, encoding][, callback]) -Example: +Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating `'0\r\n\r\n'`. - response.removeHeader("Content-Encoding"); +If `data` is specified, it is equivalent to calling +`request.write(data, encoding)` followed by `request.end(callback)`. +If `callback` is specified, it will be called when the request stream +is finished. -### response.write(chunk[, encoding][, callback]) +### request.flushHeaders() -If this method is called and [response.writeHead()][] has not been called, -it will switch to implicit header mode and flush the implicit headers. +Flush the request headers. -This sends a chunk of the response body. This method may -be called multiple times to provide successive parts of the body. +For efficiency reasons, Node.js normally buffers the request headers until you +call `request.end()` or write the first chunk of request data. It then tries +hard to pack the request headers and data into a single TCP packet. -`chunk` can be a string or a buffer. If `chunk` is a string, -the second parameter specifies how to encode it into a byte stream. -By default the `encoding` is `'utf8'`. The last parameter `callback` -will be called when this chunk of data is flushed. +That's usually what you want (it saves a TCP round-trip) but not when the first +data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass +the optimization and kickstart the request. -**Note**: This is the raw HTTP body and has nothing to do with -higher-level multi-part body encodings that may be used. +### request.setNoDelay([noDelay]) -The first time `response.write()` is called, it will send the buffered -header information and the first body to the client. The second time -`response.write()` is called, Node.js assumes you're going to be streaming -data, and sends that separately. That is, the response is buffered up to the -first chunk of body. +Once a socket is assigned to this request and is connected +[socket.setNoDelay()][] will be called. -Returns `true` if the entire data was flushed successfully to the kernel -buffer. Returns `false` if all or part of the data was queued in user memory. -`'drain'` will be emitted when the buffer is free again. +### request.setSocketKeepAlive([enable][, initialDelay]) -### response.addTrailers(headers) +Once a socket is assigned to this request and is connected +[socket.setKeepAlive()][] will be called. -This method adds HTTP trailing headers (a header but at the end of the -message) to the response. +### request.setTimeout(timeout[, callback]) -Trailers will **only** be emitted if chunked encoding is used for the -response; if it is not (e.g., if the request was HTTP/1.0), they will -be silently discarded. +Once a socket is assigned to this request and is connected +[socket.setTimeout()][] will be called. -Note that HTTP requires the `Trailer` header to be sent if you intend to -emit trailers, with a list of the header fields in its value. E.g., +### request.write(chunk[, encoding][, callback]) - response.writeHead(200, { 'Content-Type': 'text/plain', - 'Trailer': 'Content-MD5' }); - response.write(fileData); - response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); - response.end(); +Sends a chunk of the body. By calling this method +many times, the user can stream a request body to a +server--in that case it is suggested to use the +`['Transfer-Encoding', 'chunked']` header line when +creating the request. +The `chunk` argument should be a [Buffer][] or a string. -### response.end([data][, encoding][, callback]) +The `encoding` argument is optional and only applies when `chunk` is a string. +Defaults to `'utf8'`. -This method signals to the server that all of the response headers and body -have been sent; that server should consider this message complete. -The method, `response.end()`, MUST be called on each -response. +The `callback` argument is optional and will be called when this chunk of data +is flushed. -If `data` is specified, it is equivalent to calling -`response.write(data, encoding)` followed by `response.end(callback)`. +Returns `request`. -If `callback` is specified, it will be called when the response stream -is finished. +## Class: http.Server -### response.finished +This is an [EventEmitter][] with the following events: -Boolean value that indicates whether the response has completed. Starts -as `false`. After `response.end()` executes, the value will be `true`. +### Event: 'checkContinue' -## http.request(options[, callback]) +`function (request, response) { }` -Node.js maintains several connections per server to make HTTP requests. -This function allows one to transparently issue requests. +Emitted each time a request with an http Expect: 100-continue is received. +If this event isn't listened for, the server will automatically respond +with a 100 Continue as appropriate. -`options` can be an object or a string. If `options` is a string, it is -automatically parsed with [url.parse()][] and it must be a valid complete URL, -including protocol and complete domain name or IP address. +Handling this event involves calling [response.writeContinue()][] if the client +should continue to send the request body, or generating an appropriate HTTP +response (e.g., 400 Bad Request) if the client should not continue to send the +request body. -**Note**: If the passed string is not in the valid URL format, then the - connection will be established to the default domain name, localhost, and on - the default port, 80. *This will be fixed soon.* +Note that when this event is emitted and handled, the `request` event will +not be emitted. -Options: +### Event: 'clientError' -- `protocol`: Protocol to use. Defaults to `'http'`. -- `host`: A domain name or IP address of the server to issue the request to. - Defaults to `'localhost'`. -- `hostname`: Alias for `host`. To support `url.parse()` `hostname` is - preferred over `host`. -- `family`: IP address family to use when resolving `host` and `hostname`. - Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be - used. -- `port`: Port of remote server. Defaults to 80. -- `localAddress`: Local interface to bind for network connections. -- `socketPath`: Unix Domain Socket (use one of host:port or socketPath). -- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. -- `path`: Request path. Defaults to `'/'`. Should include query string if any. - E.G. `'/index.html?page=12'`. An exception is thrown when the request path - contains illegal characters. Currently, only spaces are rejected but that - may change in the future. -- `headers`: An object containing request headers. -- `auth`: Basic authentication i.e. `'user:password'` to compute an - Authorization header. -- `agent`: Controls [Agent][] behavior. When an Agent is used request will - default to `Connection: keep-alive`. Possible values: - - `undefined` (default): use [globalAgent][] for this host and port. - - `Agent` object: explicitly use the passed in `Agent`. - - `false`: opts out of connection pooling with an Agent, defaults request to - `Connection: close`. +`function (exception, socket) { }` -The optional `callback` parameter will be added as a one time listener for -the ['response'][] event. +If a client connection emits an 'error' event, it will be forwarded here. -`http.request()` returns an instance of the [http.ClientRequest][] -class. The `ClientRequest` instance is a writable stream. If one needs to -upload a file with a POST request, then write to the `ClientRequest` object. +`socket` is the `net.Socket` object that the error originated from. -Example: +### Event: 'close' - var postData = querystring.stringify({ - 'msg' : 'Hello World!' - }); +`function () { }` - var options = { - hostname: 'www.google.com', - port: 80, - path: '/upload', - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Content-Length': postData.length - } - }; +Emitted when the server closes. - var req = http.request(options, function(res) { - console.log('STATUS: ' + res.statusCode); - console.log('HEADERS: ' + JSON.stringify(res.headers)); - res.setEncoding('utf8'); - res.on('data', function (chunk) { - console.log('BODY: ' + chunk); - }); - res.on('end', function() { - console.log('No more data in response.') - }) - }); +### Event: 'connect' - req.on('error', function(e) { - console.log('problem with request: ' + e.message); - }); +`function (request, socket, head) { }` - // write data to request body - req.write(postData); - req.end(); +Emitted each time a client requests a http CONNECT method. If this event isn't +listened for, then clients requesting a CONNECT method will have their +connections closed. -Note that in the example `req.end()` was called. With `http.request()` one -must always call `req.end()` to signify that you're done with the request - -even if there is no data being written to the request body. +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the tunneling stream, + this may be empty. -If any error is encountered during the request (be that with DNS resolution, -TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted -on the returned request object. +After this event is emitted, the request's socket will not have a `data` +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. -There are a few special headers that should be noted. +### Event: 'connection' -* Sending a 'Connection: keep-alive' will notify Node.js that the connection to - the server should be persisted until the next request. +`function (socket) { }` -* Sending a 'Content-length' header will disable the default chunked encoding. +When a new TCP stream is established. `socket` is an object of type +`net.Socket`. Usually users will not want to access this event. In +particular, the socket will not emit `readable` events because of how +the protocol parser attaches to the socket. The `socket` can also be +accessed at `request.connection`. -* Sending an 'Expect' header will immediately send the request headers. - Usually, when sending 'Expect: 100-continue', you should both set a timeout - and listen for the `continue` event. See RFC2616 Section 8.2.3 for more - information. +### Event: 'request' -* Sending an Authorization header will override using the `auth` option - to compute basic authentication. +`function (request, response) { }` -## http.get(options[, callback]) +Emitted each time there is a request. Note that there may be multiple requests +per connection (in the case of keep-alive connections). + `request` is an instance of [http.IncomingMessage][] and `response` is +an instance of [http.ServerResponse][]. -Since most requests are GET requests without bodies, Node.js provides this -convenience method. The only difference between this method and [http.request][] -is that it sets the method to GET and calls `req.end()` automatically. +### Event: 'upgrade' -Example: +`function (request, socket, head) { }` - http.get("http://www.google.com/index.html", function(res) { - console.log("Got response: " + res.statusCode); - }).on('error', function(e) { - console.log("Got error: " + e.message); - }); +Emitted each time a client requests a http upgrade. If this event isn't +listened for, then clients requesting an upgrade will have their connections +closed. +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the upgraded stream, + this may be empty. -## Class: http.Agent +After this event is emitted, the request's socket will not have a `data` +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. -The HTTP Agent is used for pooling sockets used in HTTP client -requests. +### server.close([callback]) -The HTTP Agent also defaults client requests to using -Connection:keep-alive. If no pending HTTP requests are waiting on a -socket to become free the socket is closed. This means that Node.js's -pool has the benefit of keep-alive when under load but still does not -require developers to manually close the HTTP clients using -KeepAlive. +Stops the server from accepting new connections. See [net.Server.close()][]. -If you opt into using HTTP KeepAlive, you can create an Agent object -with that flag set to `true`. (See the [constructor -options](#http_new_agent_options) below.) Then, the Agent will keep -unused sockets in a pool for later use. They will be explicitly -marked so as to not keep the Node.js process running. However, it is -still a good idea to explicitly [`destroy()`](#http_agent_destroy) -KeepAlive agents when they are no longer in use, so that the Sockets -will be shut down. +### server.listen(handle[, callback]) -Sockets are removed from the agent's pool when the socket emits either -a "close" event or a special "agentRemove" event. This means that if -you intend to keep one HTTP request open for a long time and don't -want it to stay in the pool you can do something along the lines of: +* `handle` {Object} +* `callback` {Function} - http.get(options, function(res) { - // Do stuff - }).on("socket", function (socket) { - socket.emit("agentRemove"); - }); +The `handle` object can be set to either a server or socket (anything +with an underlying `_handle` member), or a `{fd: }` object. -Alternatively, you could just opt out of pooling entirely using -`agent:false`: +This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. - http.get({ - hostname: 'localhost', - port: 80, - path: '/', - agent: false // create a new agent just for this one request - }, function (res) { - // Do stuff with response - }) +Listening on a file descriptor is not supported on Windows. -### new Agent([options]) +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'](net.html#net_event_listening) event. +See also [net.Server.listen()](net.html#net_server_listen_handle_callback). -* `options` {Object} Set of configurable options to set on the agent. - Can have the following fields: - * `keepAlive` {Boolean} Keep sockets around in a pool to be used by - other requests in the future. Default = `false` - * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often - to send TCP KeepAlive packets over sockets being kept alive. - Default = `1000`. Only relevant if `keepAlive` is set to `true`. - * `maxSockets` {Number} Maximum number of sockets to allow per - host. Default = `Infinity`. - * `maxFreeSockets` {Number} Maximum number of sockets to leave open - in a free state. Only relevant if `keepAlive` is set to `true`. - Default = `256`. +### server.listen(path[, callback]) -The default `http.globalAgent` that is used by `http.request` has all -of these values set to their respective defaults. +Start a UNIX socket server listening for connections on the given `path`. -To configure any of them, you must create your own `Agent` object. +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. -```javascript -var http = require('http'); -var keepAliveAgent = new http.Agent({ keepAlive: true }); -options.agent = keepAliveAgent; -http.request(options, onResponseCallback); -``` +### server.listen(port[, hostname][, backlog][, callback]) -### agent.maxSockets +Begin accepting connections on the specified `port` and `hostname`. If the +`hostname` is omitted, the server will accept connections on any IPv6 address +(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A +port value of zero will assign a random port. -By default set to Infinity. Determines how many concurrent sockets the agent -can have open per origin. Origin is either a 'host:port' or -'host:port:localAddress' combination. +To listen to a unix socket, supply a filename instead of port and hostname. -### agent.maxFreeSockets +Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this +parameter is 511 (not 512). -By default set to 256. For Agents supporting HTTP KeepAlive, this -sets the maximum number of sockets that will be left open in the free -state. +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. -### agent.sockets +### server.maxHeadersCount -An object which contains arrays of sockets currently in use by the -Agent. Do not modify. +Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - +no limit will be applied. -### agent.freeSockets +### server.setTimeout(msecs, callback) -An object which contains arrays of sockets currently awaiting use by -the Agent when HTTP KeepAlive is used. Do not modify. +* `msecs` {Number} +* `callback` {Function} -### agent.requests +Sets the timeout value for sockets, and emits a `'timeout'` event on +the Server object, passing the socket as an argument, if a timeout +occurs. -An object which contains queues of requests that have not yet been assigned to -sockets. Do not modify. +If there is a `'timeout'` event listener on the Server object, then it +will be called with the timed-out socket as an argument. -### agent.destroy() +By default, the Server's timeout value is 2 minutes, and sockets are +destroyed automatically if they time out. However, if you assign a +callback to the Server's `'timeout'` event, then you are responsible +for handling socket timeouts. -Destroy any sockets that are currently in use by the agent. +Returns `server`. -It is usually not necessary to do this. However, if you are using an -agent with KeepAlive enabled, then it is best to explicitly shut down -the agent when you know that it will no longer be used. Otherwise, -sockets may hang open for quite a long time before the server -terminates them. +### server.timeout -### agent.getName(options) +* {Number} Default = 120000 (2 minutes) -Get a unique name for a set of request options, to determine whether a -connection can be reused. In the http agent, this returns -`host:port:localAddress`. In the https agent, the name includes the -CA, cert, ciphers, and other HTTPS/TLS-specific options that determine -socket reusability. +The number of milliseconds of inactivity before a socket is presumed +to have timed out. + +Note that the socket timeout logic is set up on connection, so +changing this value only affects *new* connections to the server, not +any existing connections. + +Set to 0 to disable any kind of automatic timeout behavior on incoming +connections. + +## Class: http.ServerResponse +This object is created internally by a HTTP server--not by the user. It is +passed as the second parameter to the `'request'` event. + +The response implements the [Writable Stream][] interface. This is an +[EventEmitter][] with the following events: -## http.globalAgent +### Event: 'close' -Global instance of Agent which is used as the default for all http client -requests. +`function () { }` +Indicates that the underlying connection was terminated before +[response.end()][] was called or able to flush. -## Class: http.ClientRequest +### Event: 'finish' -This object is created internally and returned from `http.request()`. It -represents an _in-progress_ request whose header has already been queued. The -header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, -`removeHeader(name)` API. The actual header will be sent along with the first -data chunk or when closing the connection. +`function () { }` -To get the response, add a listener for `'response'` to the request object. -`'response'` will be emitted from the request object when the response -headers have been received. The `'response'` event is executed with one -argument which is an instance of [http.IncomingMessage][]. +Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the operating system for transmission over the network. It +does not imply that the client has received anything yet. -During the `'response'` event, one can add listeners to the -response object; particularly to listen for the `'data'` event. +After this event, no more events will be emitted on the response object. -If no `'response'` handler is added, then the response will be -entirely discarded. However, if you add a `'response'` event handler, -then you **must** consume the data from the response object, either by -calling `response.read()` whenever there is a `'readable'` event, or -by adding a `'data'` handler, or by calling the `.resume()` method. -Until the data is consumed, the `'end'` event will not fire. Also, until -the data is read it will consume memory that can eventually lead to a -'process out of memory' error. +### response.addTrailers(headers) -Note: Node.js does not check whether Content-Length and the length of the body -which has been transmitted are equal or not. +This method adds HTTP trailing headers (a header but at the end of the +message) to the response. -The request implements the [Writable Stream][] interface. This is an -[EventEmitter][] with the following events: +Trailers will **only** be emitted if chunked encoding is used for the +response; if it is not (e.g., if the request was HTTP/1.0), they will +be silently discarded. -### Event: 'response' +Note that HTTP requires the `Trailer` header to be sent if you intend to +emit trailers, with a list of the header fields in its value. E.g., -`function (response) { }` + response.writeHead(200, { 'Content-Type': 'text/plain', + 'Trailer': 'Content-MD5' }); + response.write(fileData); + response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); + response.end(); -Emitted when a response is received to this request. This event is emitted only -once. The `response` argument will be an instance of [http.IncomingMessage][]. +Attempting to set a trailer field name that contains invalid characters will +result in a `TypeError` being thrown. -Options: +### response.end([data][, encoding][, callback]) -- `host`: A domain name or IP address of the server to issue the request to. -- `port`: Port of remote server. -- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) +This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, `response.end()`, MUST be called on each +response. -### Event: 'socket' +If `data` is specified, it is equivalent to calling +`response.write(data, encoding)` followed by `response.end(callback)`. -`function (socket) { }` +If `callback` is specified, it will be called when the response stream +is finished. -Emitted after a socket is assigned to this request. +### response.finished -### Event: 'connect' +Boolean value that indicates whether the response has completed. Starts +as `false`. After `response.end()` executes, the value will be `true`. -`function (response, socket, head) { }` +### response.getHeader(name) -Emitted each time a server responds to a request with a CONNECT method. If this -event isn't being listened for, clients receiving a CONNECT method will have -their connections closed. +Reads out a header that's already been queued but not sent to the client. Note +that the name is case insensitive. This can only be called before headers get +implicitly flushed. -A client server pair that show you how to listen for the `connect` event. +Example: - var http = require('http'); - var net = require('net'); - var url = require('url'); + var contentType = response.getHeader('content-type'); - // Create an HTTP tunneling proxy - var proxy = http.createServer(function (req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('okay'); - }); - proxy.on('connect', function(req, cltSocket, head) { - // connect to an origin server - var srvUrl = url.parse('http://' + req.url); - var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { - cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + - 'Proxy-agent: Node.js-Proxy\r\n' + - '\r\n'); - srvSocket.write(head); - srvSocket.pipe(cltSocket); - cltSocket.pipe(srvSocket); - }); - }); +### response.headersSent - // now that proxy is running - proxy.listen(1337, '127.0.0.1', function() { +Boolean (read-only). True if headers were sent, false otherwise. - // make a request to a tunneling proxy - var options = { - port: 1337, - hostname: '127.0.0.1', - method: 'CONNECT', - path: 'www.google.com:80' - }; +### response.removeHeader(name) - var req = http.request(options); - req.end(); +Removes a header that's queued for implicit sending. - req.on('connect', function(res, socket, head) { - console.log('got connected!'); +Example: - // make a request over an HTTP tunnel - socket.write('GET / HTTP/1.1\r\n' + - 'Host: www.google.com:80\r\n' + - 'Connection: close\r\n' + - '\r\n'); - socket.on('data', function(chunk) { - console.log(chunk.toString()); - }); - socket.on('end', function() { - proxy.close(); - }); - }); - }); + response.removeHeader("Content-Encoding"); -### Event: 'upgrade' +### response.sendDate -`function (response, socket, head) { }` +When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true. -Emitted each time a server responds to a request with an upgrade. If this -event isn't being listened for, clients receiving an upgrade header will have -their connections closed. +This should only be disabled for testing; HTTP requires the Date header +in responses. -A client server pair that show you how to listen for the `upgrade` event. +### response.setHeader(name, value) - var http = require('http'); +Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here if you need to send multiple headers with the same name. - // Create an HTTP server - var srv = http.createServer(function (req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('okay'); - }); - srv.on('upgrade', function(req, socket, head) { - socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n'); +Example: - socket.pipe(socket); // echo back - }); + response.setHeader("Content-Type", "text/html"); - // now that server is running - srv.listen(1337, '127.0.0.1', function() { +or - // make a request - var options = { - port: 1337, - hostname: '127.0.0.1', - headers: { - 'Connection': 'Upgrade', - 'Upgrade': 'websocket' - } - }; + response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); - var req = http.request(options); - req.end(); +Attempting to set a header field name that contains invalid characters will +result in a `TypeError` being thrown. - req.on('upgrade', function(res, socket, upgradeHead) { - console.log('got upgraded!'); - socket.end(); - process.exit(0); - }); - }); +### response.setTimeout(msecs, callback) -### Event: 'continue' +* `msecs` {Number} +* `callback` {Function} -`function () { }` +Sets the Socket's timeout value to `msecs`. If a callback is +provided, then it is added as a listener on the `'timeout'` event on +the response object. -Emitted when the server sends a '100 Continue' HTTP response, usually because -the request contained 'Expect: 100-continue'. This is an instruction that -the client should send the request body. +If no `'timeout'` listener is added to the request, the response, or +the server, then sockets are destroyed when they time out. If you +assign a handler on the request, the response, or the server's +`'timeout'` events, then it is your responsibility to handle timed out +sockets. -### Event: 'abort' +Returns `response`. -`function () { }` +### response.statusCode -Emitted when the request has been aborted by the client. This event is only -emitted on the first call to `abort()`. +When using implicit headers (not calling [response.writeHead()][] explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed. -### request.flushHeaders() +Example: -Flush the request headers. + response.statusCode = 404; -For efficiency reasons, Node.js normally buffers the request headers until you -call `request.end()` or write the first chunk of request data. It then tries -hard to pack the request headers and data into a single TCP packet. +After response header was sent to the client, this property indicates the +status code which was sent out. -That's usually what you want (it saves a TCP round-trip) but not when the first -data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass -the optimization and kickstart the request. +### response.statusMessage -### request.write(chunk[, encoding][, callback]) +When using implicit headers (not calling `response.writeHead()` explicitly), this property +controls the status message that will be sent to the client when the headers get +flushed. If this is left as `undefined` then the standard message for the status +code will be used. -Sends a chunk of the body. By calling this method -many times, the user can stream a request body to a -server--in that case it is suggested to use the -`['Transfer-Encoding', 'chunked']` header line when -creating the request. +Example: -The `chunk` argument should be a [Buffer][] or a string. + response.statusMessage = 'Not found'; -The `encoding` argument is optional and only applies when `chunk` is a string. -Defaults to `'utf8'`. +After response header was sent to the client, this property indicates the +status message which was sent out. -The `callback` argument is optional and will be called when this chunk of data -is flushed. +### response.write(chunk[, encoding][, callback]) -### request.end([data][, encoding][, callback]) +If this method is called and [response.writeHead()][] has not been called, +it will switch to implicit header mode and flush the implicit headers. -Finishes sending the request. If any parts of the body are -unsent, it will flush them to the stream. If the request is -chunked, this will send the terminating `'0\r\n\r\n'`. +This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body. -If `data` is specified, it is equivalent to calling -`request.write(data, encoding)` followed by `request.end(callback)`. +`chunk` can be a string or a buffer. If `chunk` is a string, +the second parameter specifies how to encode it into a byte stream. +By default the `encoding` is `'utf8'`. The last parameter `callback` +will be called when this chunk of data is flushed. -If `callback` is specified, it will be called when the request stream -is finished. +**Note**: This is the raw HTTP body and has nothing to do with +higher-level multi-part body encodings that may be used. -### request.abort() +The first time `response.write()` is called, it will send the buffered +header information and the first body to the client. The second time +`response.write()` is called, Node.js assumes you're going to be streaming +data, and sends that separately. That is, the response is buffered up to the +first chunk of body. -Marks the request as aborting. Calling this will cause remaining data -in the response to be dropped and the socket to be destroyed. +Returns `true` if the entire data was flushed successfully to the kernel +buffer. Returns `false` if all or part of the data was queued in user memory. +`'drain'` will be emitted when the buffer is free again. -### request.setTimeout(timeout[, callback]) +### response.writeContinue() -Once a socket is assigned to this request and is connected -[socket.setTimeout()][] will be called. +Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the ['checkContinue'][] event on `Server`. -Returns `request`. +### response.writeHead(statusCode[, statusMessage][, headers]) -### request.setNoDelay([noDelay]) +Sends a response header to the request. The status code is a 3-digit HTTP +status code, like `404`. The last argument, `headers`, are the response headers. +Optionally one can give a human-readable `statusMessage` as the second +argument. -Once a socket is assigned to this request and is connected -[socket.setNoDelay()][] will be called. +Example: -### request.setSocketKeepAlive([enable][, initialDelay]) + var body = 'hello world'; + response.writeHead(200, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' }); -Once a socket is assigned to this request and is connected -[socket.setKeepAlive()][] will be called. +This method must only be called once on a message and it must +be called before [response.end()][] is called. + +If you call [response.write()][] or [response.end()][] before calling this, the +implicit/mutable headers will be calculated and call this function for you. +Note that Content-Length is given in bytes not characters. The above example +works because the string `'hello world'` contains only single byte characters. +If the body contains higher coded characters then `Buffer.byteLength()` +should be used to determine the number of bytes in a given encoding. +And Node.js does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. ## http.IncomingMessage @@ -961,15 +802,6 @@ following additional events, methods, and properties. Indicates that the underlying connection was closed. Just like `'end'`, this event occurs only once per response. -### message.httpVersion - -In case of server request, the HTTP version sent by the client. In the case of -client response, the HTTP version of the connected-to server. -Probably either `'1.1'` or `'1.0'`. - -Also `response.httpVersionMajor` is the first integer and -`response.httpVersionMinor` is the second. - ### message.headers The request/response headers object. @@ -984,6 +816,22 @@ Example: // accept: '*/*' } console.log(request.headers); +### message.httpVersion + +In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. +Probably either `'1.1'` or `'1.0'`. + +Also `response.httpVersionMajor` is the first integer and +`response.httpVersionMinor` is the second. + +### message.method + +**Only valid for request obtained from [http.Server][].** + +The request method as a string. Read only. Example: +`'GET'`, `'DELETE'`. + ### message.rawHeaders The raw request/response headers list exactly as they were received. @@ -1006,10 +854,6 @@ Header names are not lowercased, and duplicates are not merged. // '*/*' ] console.log(request.rawHeaders); -### message.trailers - -The request/response trailers object. Only populated at the 'end' event. - ### message.rawTrailers The raw request/response trailer keys and values exactly as they were @@ -1024,12 +868,28 @@ Calls `message.connection.setTimeout(msecs, callback)`. Returns `message`. -### message.method +### message.statusCode -**Only valid for request obtained from [http.Server][].** +**Only valid for response obtained from `http.ClientRequest`.** -The request method as a string. Read only. Example: -`'GET'`, `'DELETE'`. +The 3-digit HTTP response status code. E.G. `404`. + +### message.statusMessage + +**Only valid for response obtained from `http.ClientRequest`.** + +### message.socket + +The `net.Socket` object associated with the connection. + +With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the +client's authentication details. + +The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + +### message.trailers + +The request/response trailers object. Only populated at the 'end' event. ### message.url @@ -1065,25 +925,155 @@ you can use the `require('querystring').parse` function, or pass query: { name: 'ryan' }, pathname: '/status' } -### message.statusCode +## http.METHODS -**Only valid for response obtained from `http.ClientRequest`.** +* {Array} -The 3-digit HTTP response status code. E.G. `404`. +A list of the HTTP methods that are supported by the parser. -### message.statusMessage +## http.STATUS_CODES -**Only valid for response obtained from `http.ClientRequest`.** +* {Object} -The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. +A collection of all the standard HTTP response status codes, and the +short description of each. For example, `http.STATUS_CODES[404] === 'Not +Found'`. -### message.socket +## http.createClient([port][, host]) -The `net.Socket` object associated with the connection. + Stability: 0 - Deprecated: Use [http.request][] instead. -With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the -client's authentication details. +Constructs a new HTTP client. `port` and `host` refer to the server to be +connected to. + +## http.createServer([requestListener]) + +Returns a new instance of [http.Server](#http_class_http_server). + +The `requestListener` is a function which is automatically +added to the `'request'` event. + +## http.get(options[, callback]) + +Since most requests are GET requests without bodies, Node.js provides this +convenience method. The only difference between this method and `http.request()` +is that it sets the method to GET and calls `req.end()` automatically. + +Example: + + http.get("http://www.google.com/index.html", function(res) { + console.log("Got response: " + res.statusCode); + }).on('error', function(e) { + console.log("Got error: " + e.message); + }); + +## http.globalAgent + +Global instance of Agent which is used as the default for all http client +requests. + +## http.request(options[, callback]) + +Node.js maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()][]. + +Options: + +- `protocol`: Protocol to use. Defaults to `'http'`. +- `host`: A domain name or IP address of the server to issue the request to. + Defaults to `'localhost'`. +- `hostname`: Alias for `host`. To support `url.parse()` `hostname` is + preferred over `host`. +- `family`: IP address family to use when resolving `host` and `hostname`. + Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be + used. +- `port`: Port of remote server. Defaults to 80. +- `localAddress`: Local interface to bind for network connections. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath). +- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. +- `path`: Request path. Defaults to `'/'`. Should include query string if any. + E.G. `'/index.html?page=12'`. An exception is thrown when the request path + contains illegal characters. Currently, only spaces are rejected but that + may change in the future. +- `headers`: An object containing request headers. +- `auth`: Basic authentication i.e. `'user:password'` to compute an + Authorization header. +- `agent`: Controls [Agent][] behavior. When an Agent is used request will + default to `Connection: keep-alive`. Possible values: + - `undefined` (default): use [globalAgent][] for this host and port. + - `Agent` object: explicitly use the passed in `Agent`. + - `false`: opts out of connection pooling with an Agent, defaults request to + `Connection: close`. + +The optional `callback` parameter will be added as a one time listener for +the ['response'][] event. + +`http.request()` returns an instance of the [http.ClientRequest][] +class. The `ClientRequest` instance is a writable stream. If one needs to +upload a file with a POST request, then write to the `ClientRequest` object. + +Example: + + var postData = querystring.stringify({ + 'msg' : 'Hello World!' + }); + + var options = { + hostname: 'www.google.com', + port: 80, + path: '/upload', + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': postData.length + } + }; + + var req = http.request(options, function(res) { + console.log('STATUS: ' + res.statusCode); + console.log('HEADERS: ' + JSON.stringify(res.headers)); + res.setEncoding('utf8'); + res.on('data', function (chunk) { + console.log('BODY: ' + chunk); + }); + res.on('end', function() { + console.log('No more data in response.') + }) + }); + + req.on('error', function(e) { + console.log('problem with request: ' + e.message); + }); + + // write data to request body + req.write(postData); + req.end(); + +Note that in the example `req.end()` was called. With `http.request()` one +must always call `req.end()` to signify that you're done with the request - +even if there is no data being written to the request body. + +If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted +on the returned request object. + +There are a few special headers that should be noted. + +* Sending a 'Connection: keep-alive' will notify Node.js that the connection to + the server should be persisted until the next request. + +* Sending a 'Content-length' header will disable the default chunked encoding. + +* Sending an 'Expect' header will immediately send the request headers. + Usually, when sending 'Expect: 100-continue', you should both set a timeout + and listen for the `continue` event. See RFC2616 Section 8.2.3 for more + information. +* Sending an Authorization header will override using the `auth` option + to compute basic authentication. ['checkContinue']: #http_event_checkcontinue ['listening']: net.html#net_event_listening