3 To use the HTTP server and client one must `require('http')`.
5 The HTTP interfaces in Node are designed to support many features
6 of the protocol which have been traditionally difficult to use.
7 In particular, large, possibly chunk-encoded, messages. The interface is
8 careful to never buffer entire requests or responses--the
9 user is able to stream data.
11 HTTP message headers are represented by an object like this:
13 { 'content-length': '123',
14 'content-type': 'text/plain',
15 'connection': 'keep-alive',
18 Keys are lowercased. Values are not modified.
20 In order to support the full spectrum of possible HTTP applications, Node's
21 HTTP API is very low-level. It deals with stream handling and message
22 parsing only. It parses a message into headers and body but it does not
23 parse the actual headers or the body.
28 This is an `EventEmitter` with the following events:
32 `function (request, response) { }`
34 Emitted each time there is request. Note that there may be multiple requests
35 per connection (in the case of keep-alive connections).
36 `request` is an instance of `http.ServerRequest` and `response` is
37 an instance of `http.ServerResponse`
39 ### Event: 'connection'
41 `function (stream) { }`
43 When a new TCP stream is established. `stream` is an object of type
44 `net.Stream`. Usually users will not want to access this event. The
45 `stream` can also be accessed at `request.connection`.
49 `function (errno) { }`
51 Emitted when the server closes.
53 ### Event: 'checkContinue'
55 `function (request, response) {}`
57 Emitted each time a request with an http Expect: 100-continue is received.
58 If this event isn't listened for, the server will automatically respond
59 with a 100 Continue as appropriate.
61 Handling this event involves calling `response.writeContinue` if the client
62 should continue to send the request body, or generating an appropriate HTTP
63 response (e.g., 400 Bad Request) if the client should not continue to send the
66 Note that when this event is emitted and handled, the `request` event will
71 `function (request, socket, head)`
73 Emitted each time a client requests a http upgrade. If this event isn't
74 listened for, then clients requesting an upgrade will have their connections
77 * `request` is the arguments for the http request, as it is in the request event.
78 * `socket` is the network socket between the server and client.
79 * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
81 After this event is emitted, the request's socket will not have a `data`
82 event listener, meaning you will need to bind to it in order to handle data
83 sent to the server on that socket.
85 ### Event: 'clientError'
87 `function (exception) {}`
89 If a client connection emits an 'error' event - it will forwarded here.
91 ### http.createServer(requestListener)
93 Returns a new web server object.
95 The `requestListener` is a function which is automatically
96 added to the `'request'` event.
98 ### server.listen(port, [hostname], [callback])
100 Begin accepting connections on the specified port and hostname. If the
101 hostname is omitted, the server will accept connections directed to any
102 IPv4 address (`INADDR_ANY`).
104 To listen to a unix socket, supply a filename instead of port and hostname.
106 This function is asynchronous. The last parameter `callback` will be called
107 when the server has been bound to the port.
110 ### server.listen(path, [callback])
112 Start a UNIX socket server listening for connections on the given `path`.
114 This function is asynchronous. The last parameter `callback` will be called
115 when the server has been bound.
120 Stops the server from accepting new connections.
123 ## http.ServerRequest
125 This object is created internally by a HTTP server -- not by
126 the user -- and passed as the first argument to a `'request'` listener.
128 This is an `EventEmitter` with the following events:
132 `function (chunk) { }`
134 Emitted when a piece of the message body is received.
136 Example: A chunk of the body is given as the single
137 argument. The transfer-encoding has been decoded. The
138 body chunk is a string. The body encoding is set with
139 `request.setBodyEncoding()`.
145 Emitted exactly once for each message. No arguments. After
146 emitted no other events will be emitted on the request.
151 The request method as a string. Read only. Example:
157 Request URL string. This contains only the URL that is
158 present in the actual HTTP request. If the request is:
160 GET /status?name=ryan HTTP/1.1\r\n
161 Accept: text/plain\r\n
164 Then `request.url` will be:
168 If you would like to parse the URL into its parts, you can use
169 `require('url').parse(request.url)`. Example:
171 node> require('url').parse('/status?name=ryan')
172 { href: '/status?name=ryan',
173 search: '?name=ryan',
175 pathname: '/status' }
177 If you would like to extract the params from the query string,
178 you can use the `require('querystring').parse` function, or pass
179 `true` as the second argument to `require('url').parse`. Example:
181 node> require('url').parse('/status?name=ryan', true)
182 { href: '/status?name=ryan',
183 search: '?name=ryan',
184 query: { name: 'ryan' },
185 pathname: '/status' }
195 Read only; HTTP trailers (if present). Only populated after the 'end' event.
197 ### request.httpVersion
199 The HTTP protocol version as a string. Read only. Examples:
201 Also `request.httpVersionMajor` is the first integer and
202 `request.httpVersionMinor` is the second.
205 ### request.setEncoding(encoding=null)
207 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
208 to `null`, which means that the `'data'` event will emit a `Buffer` object..
213 Pauses request from emitting events. Useful to throttle back an upload.
218 Resumes a paused request.
220 ### request.connection
222 The `net.Stream` object associated with the connection.
225 With HTTPS support, use request.connection.verifyPeer() and
226 request.connection.getPeerCertificate() to obtain the client's
227 authentication details.
231 ## http.ServerResponse
233 This object is created internally by a HTTP server--not by the user. It is
234 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
236 ### response.writeContinue()
238 Sends a HTTP/1.1 100 Continue message to the client, indicating that
239 the request body should be sent. See the [checkContinue](#event_checkContinue_) event on
242 ### response.writeHead(statusCode, [reasonPhrase], [headers])
244 Sends a response header to the request. The status code is a 3-digit HTTP
245 status code, like `404`. The last argument, `headers`, are the response headers.
246 Optionally one can give a human-readable `reasonPhrase` as the second
251 var body = 'hello world';
252 response.writeHead(200, {
253 'Content-Length': body.length,
254 'Content-Type': 'text/plain' });
256 This method must only be called once on a message and it must
257 be called before `response.end()` is called.
259 If you call `response.write()` or `response.end()` before calling this, the
260 implicit/mutable headers will be calculated and call this function for you.
262 ### response.statusCode
264 When using implicit headers (not calling `response.writeHead()` explicitly), this property
265 controls the status code that will be send to the client when the headers get
270 response.statusCode = 404;
272 ### response.setHeader(name, value)
274 Sets a single header value for implicit headers. If this header already exists
275 in the to-be-sent headers, it's value will be replaced. Use an array of strings
276 here if you need to send multiple headers with the same name.
280 response.setHeader("Content-Type", "text/html");
284 response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
287 ### response.getHeader(name)
289 Reads out a header that's already been queued but not sent to the client. Note
290 that the name is case insensitive. This can only be called before headers get
295 var contentType = response.getHeader('content-type');
297 ### response.removeHeader(name)
299 Removes a header that's queued for implicit sending.
303 response.removeHeader("Content-Encoding");
306 ### response.write(chunk, encoding='utf8')
308 If this method is called and `response.writeHead()` has not been called, it will
309 switch to implicit header mode and flush the implicit headers.
311 This sends a chunk of the response body. This method may
312 be called multiple times to provide successive parts of the body.
314 `chunk` can be a string or a buffer. If `chunk` is a string,
315 the second parameter specifies how to encode it into a byte stream.
316 By default the `encoding` is `'utf8'`.
318 **Note**: This is the raw HTTP body and has nothing to do with
319 higher-level multi-part body encodings that may be used.
321 The first time `response.write()` is called, it will send the buffered
322 header information and the first body to the client. The second time
323 `response.write()` is called, Node assumes you're going to be streaming
324 data, and sends that separately. That is, the response is buffered up to the
327 ### response.addTrailers(headers)
329 This method adds HTTP trailing headers (a header but at the end of the
330 message) to the response.
332 Trailers will **only** be emitted if chunked encoding is used for the
333 response; if it is not (e.g., if the request was HTTP/1.0), they will
334 be silently discarded.
336 Note that HTTP requires the `Trailer` header to be sent if you intend to
337 emit trailers, with a list of the header fields in its value. E.g.,
339 response.writeHead(200, { 'Content-Type': 'text/plain',
340 'Trailer': 'TraceInfo' });
341 response.write(fileData);
342 response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
346 ### response.end([data], [encoding])
348 This method signals to the server that all of the response headers and body
349 has been sent; that server should consider this message complete.
350 The method, `response.end()`, MUST be called on each
353 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
354 followed by `response.end()`.
357 ## http.request(options, callback)
359 Node maintains several connections per server to make HTTP requests.
360 This function allows one to transparently issue requests.
364 - `host`: A domain name or IP address of the server to issue the request to.
365 - `port`: Port of remote server.
366 - `method`: A string specifying the HTTP request method. Possible values:
367 `'GET'` (default), `'POST'`, `'PUT'`, and `'DELETE'`.
368 - `path`: Request path. Should include query string and fragments if any.
369 E.G. `'/index.html?page=12'`
370 - `headers`: An object containing request headers.
372 `http.request()` returns an instance of the `http.ClientRequest`
373 class. The `ClientRequest` instance is a writable stream. If one needs to
374 upload a file with a POST request, then write to the `ClientRequest` object.
379 host: 'www.google.com',
385 var req = http.request(options, function(res) {
386 console.log('STATUS: ' + res.statusCode);
387 console.log('HEADERS: ' + JSON.stringify(res.headers));
388 res.setEncoding('utf8');
389 res.on('data', function (chunk) {
390 console.log('BODY: ' + chunk);
394 // write data to request body
399 Note that in the example `req.end()` was called. With `http.request()` one
400 must always call `req.end()` to signify that you're done with the request -
401 even if there is no data being written to the request body.
403 If any error is encountered during the request (be that with DNS resolution,
404 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
405 on the returned request object.
407 There are a few special headers that should be noted.
409 * Sending a 'Connection: keep-alive' will notify Node that the connection to
410 the server should be persisted until the next request.
412 * Sending a 'Content-length' header will disable the default chunked encoding.
414 * Sending an 'Expect' header will immediately send the request headers.
415 Usually, when sending 'Expect: 100-continue', you should both set a timeout
416 and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
419 ## http.get(options, callback)
421 Since most requests are GET requests without bodies, Node provides this
422 convenience method. The only difference between this method and `http.request()` is
423 that it sets the method to GET and calls `req.end()` automatically.
428 host: 'www.google.com',
433 http.get(options, function(res) {
434 console.log("Got response: " + res.statusCode);
435 }).on('error', function(e) {
436 console.log("Got error: " + e.message);
441 ## http.getAgent(host, port)
443 `http.request()` uses a special `Agent` for managing multiple connections to
444 an HTTP server. Normally `Agent` instances should not be exposed to user
445 code, however in certain situations it's useful to check the status of the
446 agent. The `http.getAgent()` function allows you to access the agents.
450 `function (request, socket, head)`
452 Emitted each time a server responds to a request with an upgrade. If this event
453 isn't being listened for, clients receiving an upgrade header will have their
456 See the description of the [upgrade event](http.html#event_upgrade_) for `http.Server` for further details.
458 ### Event: 'continue'
462 Emitted when the server sends a '100 Continue' HTTP response, usually because
463 the request contained 'Expect: 100-continue'. This is an instruction that
464 the client should send the request body.
468 By default set to 5. Determines how many concurrent sockets the agent can have open.
472 An array of sockets currently in use by the Agent. Do not modify.
476 A queue of requests waiting to be sent to sockets.
480 ## http.ClientRequest
482 This object is created internally and returned from `http.request()`. It
483 represents an _in-progress_ request whose header has already been queued. The
484 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
485 `removeHeader(name)` API. The actual header will be sent along with the first
486 data chunk or when closing the connection.
488 To get the response, add a listener for `'response'` to the request object.
489 `'response'` will be emitted from the request object when the response
490 headers have been received. The `'response'` event is executed with one
491 argument which is an instance of `http.ClientResponse`.
493 During the `'response'` event, one can add listeners to the
494 response object; particularly to listen for the `'data'` event. Note that
495 the `'response'` event is called before any part of the response body is received,
496 so there is no need to worry about racing to catch the first part of the
497 body. As long as a listener for `'data'` is added during the `'response'`
498 event, the entire body will be caught.
502 request.on('response', function (response) {
503 response.on('data', function (chunk) {
504 console.log('BODY: ' + chunk);
508 // Bad - misses all or part of the body
509 request.on('response', function (response) {
510 setTimeout(function () {
511 response.on('data', function (chunk) {
512 console.log('BODY: ' + chunk);
517 This is a `Writable Stream`.
519 This is an `EventEmitter` with the following events:
523 `function (response) { }`
525 Emitted when a response is received to this request. This event is emitted only once. The
526 `response` argument will be an instance of `http.ClientResponse`.
529 ### request.write(chunk, encoding='utf8')
531 Sends a chunk of the body. By calling this method
532 many times, the user can stream a request body to a
533 server--in that case it is suggested to use the
534 `['Transfer-Encoding', 'chunked']` header line when
535 creating the request.
537 The `chunk` argument should be an array of integers
540 The `encoding` argument is optional and only
541 applies when `chunk` is a string.
544 ### request.end([data], [encoding])
546 Finishes sending the request. If any parts of the body are
547 unsent, it will flush them to the stream. If the request is
548 chunked, this will send the terminating `'0\r\n\r\n'`.
550 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
551 followed by `request.end()`.
555 Aborts a request. (New since v0.3.8.)
558 ## http.ClientResponse
560 This object is created when making a request with `http.request()`. It is
561 passed to the `'response'` event of the request object.
563 The response implements the `Readable Stream` interface.
567 `function (chunk) {}`
569 Emitted when a piece of the message body is received.
576 Emitted exactly once for each message. No arguments. After
577 emitted no other events will be emitted on the response.
579 ### response.statusCode
581 The 3-digit HTTP response status code. E.G. `404`.
583 ### response.httpVersion
585 The HTTP version of the connected-to server. Probably either
587 Also `response.httpVersionMajor` is the first integer and
588 `response.httpVersionMinor` is the second.
592 The response headers object.
594 ### response.trailers
596 The response trailers object. Only populated after the 'end' event.
598 ### response.setEncoding(encoding=null)
600 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
601 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
605 Pauses response from emitting events. Useful to throttle back a download.
607 ### response.resume()
609 Resumes a paused response.