{ "source": "doc/api/http.markdown", "modules": [ { "textRaw": "HTTP", "name": "http", "stability": 3, "stabilityText": "Stable", "desc": "

To use the HTTP server and client one must require('http').\n\n

\n

The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

\n

HTTP message headers are represented by an object like this:\n\n

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
\n

Keys are lowercased. Values are not modified.\n\n

\n

In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

\n", "properties": [ { "textRaw": "`STATUS_CODES` {Object} ", "name": "STATUS_CODES", "desc": "

A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

\n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

\n" }, { "textRaw": "http.IncomingMessage", "name": "IncomingMessage", "desc": "

An IncomingMessage object is created by http.Server or http.ClientRequest\nand passed as the first argument to the 'request' and 'response' event\nrespectively. It may be used to access response status, headers and data.\n\n

\n

It implements the [Readable Stream][] interface, as well as the\nfollowing additional events, methods, and properties.\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n

Just like 'end', this event occurs only once per response. See\n[http.ServerResponse][]'s 'close' event for more information.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "message.httpVersion", "name": "httpVersion", "desc": "

In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.\n\n

\n

Also response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

\n" }, { "textRaw": "message.headers", "name": "headers", "desc": "

The request/response headers object.\n\n

\n

Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

\n
// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
\n" }, { "textRaw": "message.trailers", "name": "trailers", "desc": "

The request/response trailers object. Only populated after the 'end' event.\n\n

\n" }, { "textRaw": "message.method", "name": "method", "desc": "

Only valid for request obtained from http.Server.\n\n

\n

The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n

\n" }, { "textRaw": "message.url", "name": "url", "desc": "

Only valid for request obtained from http.Server.\n\n

\n

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\n

Then request.url will be:\n\n

\n
'/status?name=ryan'
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

\n
node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
\n

If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

\n
node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
\n" }, { "textRaw": "message.statusCode", "name": "statusCode", "desc": "

Only valid for response obtained from http.ClientRequest.\n\n

\n

The 3-digit HTTP response status code. E.G. 404.\n\n

\n" }, { "textRaw": "message.socket", "name": "socket", "desc": "

The net.Socket object associated with the connection.\n\n

\n

With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n

\n" } ], "methods": [ { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Calls message.connection.setTimeout(msecs, callback).\n\n

\n" } ] } ], "methods": [ { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "

Returns a new web server object.\n\n

\n

The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

\n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.createClient([port], [host])", "type": "method", "name": "createClient", "desc": "

This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

\n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.request(options, callback)", "type": "method", "name": "request", "desc": "

Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Options:\n\n

\n\n

http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

\n

Example:\n\n

\n
var options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

\n

If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

\n

There are a few special headers that should be noted.\n\n

\n\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "http.get(options, callback)", "type": "method", "name": "get", "desc": "

Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

\n

Example:\n\n

\n
http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] } ], "classes": [ { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "desc": "

This is an [EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'request'", "type": "event", "name": "request", "desc": "

function (request, response) { }\n\n

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of http.IncomingMessage and response is\n an instance of http.ServerResponse\n\n

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "desc": "

function (socket) { }\n\n

\n

When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. In\n particular, the socket will not emit readable events because of how\n the protocol parser attaches to the socket. The socket can also be\n accessed at request.connection.\n\n

\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Emitted when the server closes.\n\n

\n", "params": [] }, { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "desc": "

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

\n

Handling this event involves calling response.writeContinue if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

\n\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

\n\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

function (exception, socket) { }\n\n

\n

If a client connection emits an 'error' event - it will forwarded here.\n\n

\n

socket is the net.Socket object that the error originated from.\n\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [hostname], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

To listen to a unix socket, supply a filename instead of port and hostname.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

\n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.\n\n

\n

If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.\n\n

\n

By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.\n\n

\n" } ], "properties": [ { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n

\n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "name": "timeout", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.\n\n

\n

Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.\n\n

\n

Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.\n\n

\n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

\n

The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Indicates that the underlying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "desc": "

Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", "type": "method", "name": "writeHead", "desc": "

Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

\n

Example:\n\n

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
\n

This method must only be called once on a message and it must\nbe called before response.end() is called.\n\n

\n

If you call response.write() or response.end() before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

\n

Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "reasonPhrase", "optional": true }, { "name": "headers", "optional": true } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.\n\n

\n

If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.\n\n

\n" }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "desc": "

Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

\n

Example:\n\n

\n
response.setHeader("Content-Type", "text/html");
\n

or\n\n

\n
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
\n", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

\n

Example:\n\n

\n
var contentType = response.getHeader('content-type');
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "desc": "

Removes a header that's queued for implicit sending.\n\n

\n

Example:\n\n

\n
response.removeHeader("Content-Encoding");
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

If this method is called and response.writeHead() has not been called, it will\nswitch to implicit header mode and flush the implicit headers.\n\n

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

\n

chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

\n

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

\n

The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

\n

Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

\n

Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
\n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data], [encoding])", "type": "method", "name": "end", "desc": "

This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

\n

If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.statusCode", "name": "statusCode", "desc": "

When using implicit headers (not calling response.writeHead() explicitly), this property\ncontrols the status code that will be sent to the client when the headers get\nflushed.\n\n

\n

Example:\n\n

\n
response.statusCode = 404;
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

\n" }, { "textRaw": "response.headersSent", "name": "headersSent", "desc": "

Boolean (read-only). True if headers were sent, false otherwise.\n\n

\n" }, { "textRaw": "response.sendDate", "name": "sendDate", "desc": "

When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.\n\n

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

\n" } ] }, { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "desc": "

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

\n

Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

\n

The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

\n

Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

\n
http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
\n

Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

\n
http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
\n", "properties": [ { "textRaw": "agent.maxSockets", "name": "maxSockets", "desc": "

By default set to 5. Determines how many concurrent sockets the agent can have\nopen per host.\n\n

\n" }, { "textRaw": "agent.sockets", "name": "sockets", "desc": "

An object which contains arrays of sockets currently in use by the Agent. Do not\nmodify.\n\n

\n" }, { "textRaw": "agent.requests", "name": "requests", "desc": "

An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.\n\n

\n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "desc": "

This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

\n

To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.IncomingMessage.\n\n

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.\n\n

\n

If no 'response' handler is added, then the response will be\nentirely discarded. However, if you add a 'response' event handler,\nthen you must consume the data from the response object, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.\n\n

\n

Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event 'response'", "type": "event", "name": "response", "desc": "

function (response) { }\n\n

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of http.IncomingMessage.\n\n

\n

Options:\n\n

\n\n", "params": [] }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "desc": "

function (socket) { }\n\n

\n

Emitted after a socket is assigned to this request.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the connect event.\n\n

\n
var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(req, cltSocket, head) {\n  // connect to an origin server\n  var srvUrl = url.parse('http://' + req.url);\n  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\n  });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', function() {\n\n  // make a request to a tunneling proxy\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('connect', function(res, socket, head) {\n    console.log('got connected!');\n\n    // make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the upgrade event.\n\n

\n
var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(req, socket, head) {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', function() {\n\n  // make a request\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('upgrade', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
\n", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "desc": "

function () { }\n\n

\n

Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "request.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

\n

The chunk argument should be a [Buffer][] or a string.\n\n

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.end([data], [encoding])", "type": "method", "name": "end", "desc": "

Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

\n

If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.abort()", "type": "method", "name": "abort", "desc": "

Aborts a request. (New since v0.3.8.)\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", "type": "method", "name": "setSocketKeepAlive", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "HTTP" } ] }