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.
25 HTTPS is supported if OpenSSL is available on the underlying platform.
29 This is an `EventEmitter` with the following events:
33 `function (request, response) { }`
35 `request` is an instance of `http.ServerRequest` and `response` is
36 an instance of `http.ServerResponse`
38 ### Event: 'connection'
40 `function (stream) { }`
42 When a new TCP stream is established. `stream` is an object of type
43 `net.Stream`. Usually users will not want to access this event. The
44 `stream` can also be accessed at `request.connection`.
48 `function (errno) { }`
50 Emitted when the server closes.
54 `function (request, response) {}`
56 Emitted each time there is request. Note that there may be multiple requests
57 per connection (in the case of keep-alive connections).
59 ### Event: 'checkContinue'
61 `function (request, response) {}`
63 Emitted each time a request with an http Expect: 100-continue is received.
64 If this event isn't listened for, the server will automatically respond
65 with a 100 Continue as appropriate.
67 Handling this event involves calling `response.writeContinue` if the client
68 should continue to send the request body, or generating an appropriate HTTP
69 response (e.g., 400 Bad Request) if the client should not continue to send the
72 Note that when this event is emitted and handled, the `request` event will
77 `function (request, socket, head)`
79 Emitted each time a client requests a http upgrade. If this event isn't
80 listened for, then clients requesting an upgrade will have their connections
83 * `request` is the arguments for the http request, as it is in the request event.
84 * `socket` is the network socket between the server and client.
85 * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
87 After this event is emitted, the request's socket will not have a `data`
88 event listener, meaning you will need to bind to it in order to handle data
89 sent to the server on that socket.
91 ### Event: 'clientError'
93 `function (exception) {}`
95 If a client connection emits an 'error' event - it will forwarded here.
97 ### http.createServer(requestListener)
99 Returns a new web server object.
101 The `requestListener` is a function which is automatically
102 added to the `'request'` event.
104 ### server.listen(port, [hostname], [callback])
106 Begin accepting connections on the specified port and hostname. If the
107 hostname is omitted, the server will accept connections directed to any
108 IPv4 address (`INADDR_ANY`).
110 To listen to a unix socket, supply a filename instead of port and hostname.
112 This function is asynchronous. The last parameter `callback` will be called
113 when the server has been bound to the port.
116 ### server.listen(path, [callback])
118 Start a UNIX socket server listening for connections on the given `path`.
120 This function is asynchronous. The last parameter `callback` will be called
121 when the server has been bound.
126 Stops the server from accepting new connections.
129 ## http.ServerRequest
131 This object is created internally by a HTTP server -- not by
132 the user -- and passed as the first argument to a `'request'` listener.
134 This is an `EventEmitter` with the following events:
138 `function (chunk) { }`
140 Emitted when a piece of the message body is received.
142 Example: A chunk of the body is given as the single
143 argument. The transfer-encoding has been decoded. The
144 body chunk is a string. The body encoding is set with
145 `request.setBodyEncoding()`.
151 Emitted exactly once for each message. No arguments. After
152 emitted no other events will be emitted on the request.
157 The request method as a string. Read only. Example:
163 Request URL string. This contains only the URL that is
164 present in the actual HTTP request. If the request is:
166 GET /status?name=ryan HTTP/1.1\r\n
167 Accept: text/plain\r\n
170 Then `request.url` will be:
174 If you would like to parse the URL into its parts, you can use
175 `require('url').parse(request.url)`. Example:
177 node> require('url').parse('/status?name=ryan')
178 { href: '/status?name=ryan',
179 search: '?name=ryan',
181 pathname: '/status' }
183 If you would like to extract the params from the query string,
184 you can use the `require('querystring').parse` function, or pass
185 `true` as the second argument to `require('url').parse`. Example:
187 node> require('url').parse('/status?name=ryan', true)
188 { href: '/status?name=ryan',
189 search: '?name=ryan',
190 query: { name: 'ryan' },
191 pathname: '/status' }
201 Read only; HTTP trailers (if present). Only populated after the 'end' event.
203 ### request.httpVersion
205 The HTTP protocol version as a string. Read only. Examples:
207 Also `request.httpVersionMajor` is the first integer and
208 `request.httpVersionMinor` is the second.
211 ### request.setEncoding(encoding=null)
213 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
214 to `null`, which means that the `'data'` event will emit a `Buffer` object..
219 Pauses request from emitting events. Useful to throttle back an upload.
224 Resumes a paused request.
226 ### request.connection
228 The `net.Stream` object associated with the connection.
231 With HTTPS support, use request.connection.verifyPeer() and
232 request.connection.getPeerCertificate() to obtain the client's
233 authentication details.
237 ## http.ServerResponse
239 This object is created internally by a HTTP server--not by the user. It is
240 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
242 ### response.writeContinue()
244 Sends a HTTP/1.1 100 Continue message to the client, indicating that
245 the request body should be sent. See the the `checkContinue` event on
248 ### response.writeHead(statusCode, [reasonPhrase], [headers])
250 Sends a response header to the request. The status code is a 3-digit HTTP
251 status code, like `404`. The last argument, `headers`, are the response headers.
252 Optionally one can give a human-readable `reasonPhrase` as the second
257 var body = 'hello world';
258 response.writeHead(200, {
259 'Content-Length': body.length,
260 'Content-Type': 'text/plain' });
262 This method must only be called once on a message and it must
263 be called before `response.end()` is called.
265 ### response.write(chunk, encoding='utf8')
267 This method must be called after `writeHead` was
268 called. It sends a chunk of the response body. This method may
269 be called multiple times to provide successive parts of the body.
271 `chunk` can be a string or a buffer. If `chunk` is a string,
272 the second parameter specifies how to encode it into a byte stream.
273 By default the `encoding` is `'utf8'`.
275 **Note**: This is the raw HTTP body and has nothing to do with
276 higher-level multi-part body encodings that may be used.
278 The first time `response.write()` is called, it will send the buffered
279 header information and the first body to the client. The second time
280 `response.write()` is called, Node assumes you're going to be streaming
281 data, and sends that separately. That is, the response is buffered up to the
284 ### response.addTrailers(headers)
286 This method adds HTTP trailing headers (a header but at the end of the
287 message) to the response.
289 Trailers will **only** be emitted if chunked encoding is used for the
290 response; if it is not (e.g., if the request was HTTP/1.0), they will
291 be silently discarded.
293 Note that HTTP requires the `Trailer` header to be sent if you intend to
294 emit trailers, with a list of the header fields in its value. E.g.,
296 response.writeHead(200, { 'Content-Type': 'text/plain',
297 'Trailer': 'TraceInfo' });
298 response.write(fileData);
299 response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
303 ### response.end([data], [encoding])
305 This method signals to the server that all of the response headers and body
306 has been sent; that server should consider this message complete.
307 The method, `response.end()`, MUST be called on each
310 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
311 followed by `response.end()`.
316 An HTTP client is constructed with a server address as its
317 argument, the returned handle is then used to issue one or more
318 requests. Depending on the server connected to, the client might
319 pipeline the requests or reestablish the stream after each
320 stream. _Currently the implementation does not pipeline requests._
322 Example of connecting to `google.com`:
324 var http = require('http');
325 var google = http.createClient(80, 'www.google.com');
326 var request = google.request('GET', '/',
327 {'host': 'www.google.com'});
329 request.on('response', function (response) {
330 console.log('STATUS: ' + response.statusCode);
331 console.log('HEADERS: ' + JSON.stringify(response.headers));
332 response.setEncoding('utf8');
333 response.on('data', function (chunk) {
334 console.log('BODY: ' + chunk);
338 There are a few special headers that should be noted.
340 * The 'Host' header is not added by Node, and is usually required by
343 * Sending a 'Connection: keep-alive' will notify Node that the connection to
344 the server should be persisted until the next request.
346 * Sending a 'Content-length' header will disable the default chunked encoding.
348 * Sending an 'Expect' header will immediately send the request headers.
349 Usually, when sending 'Expect: 100-continue', you should both set a timeout
350 and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
356 `function (request, socket, head)`
358 Emitted each time a server responds to a request with an upgrade. If this event
359 isn't being listened for, clients receiving an upgrade header will have their
362 See the description of the `upgrade` event for `http.Server` for further details.
364 ### Event: 'continue'
368 Emitted when the server sends a '100 Continue' HTTP response, usually because
369 the request contained 'Expect: 100-continue'. This is an instruction that
370 the client should send the request body.
373 ### http.createClient(port, host='localhost', secure=false, [credentials])
375 Constructs a new HTTP client. `port` and
376 `host` refer to the server to be connected to. A
377 stream is not established until a request is issued.
379 `secure` is an optional boolean flag to enable https support and `credentials` is an optional
380 credentials object from the crypto module, which may hold the client's private key,
381 certificate, and a list of trusted CA certificates.
383 If the connection is secure, but no explicit CA certificates are passed
384 in the credentials, then node.js will default to the publicly trusted list
385 of CA certificates, as given in <http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.
387 ### client.request(method='GET', path, [request_headers])
389 Issues a request; if necessary establishes stream. Returns a `http.ClientRequest` instance.
391 `method` is optional and defaults to 'GET' if omitted.
393 `request_headers` is optional.
394 Additional request headers might be added internally
395 by Node. Returns a `ClientRequest` object.
397 Do remember to include the `Content-Length` header if you
398 plan on sending a body. If you plan on streaming the body, perhaps
399 set `Transfer-Encoding: chunked`.
401 *NOTE*: the request is not complete. This method only sends the header of
402 the request. One needs to call `request.end()` to finalize the request and
403 retrieve the response. (This sounds convoluted but it provides a chance for
404 the user to stream a body to the server with `request.write()`.)
406 ### client.verifyPeer()
408 Returns true or false depending on the validity of the server's certificate
409 in the context of the defined or default list of trusted CA certificates.
411 ### client.getPeerCertificate()
413 Returns a JSON structure detailing the server's certificate, containing a dictionary
414 with keys for the certificate `'subject'`, `'issuer'`, `'valid_from'` and `'valid_to'`.
417 ## http.ClientRequest
419 This object is created internally and returned from the `request()` method
420 of a `http.Client`. It represents an _in-progress_ request whose header has
423 To get the response, add a listener for `'response'` to the request object.
424 `'response'` will be emitted from the request object when the response
425 headers have been received. The `'response'` event is executed with one
426 argument which is an instance of `http.ClientResponse`.
428 During the `'response'` event, one can add listeners to the
429 response object; particularly to listen for the `'data'` event. Note that
430 the `'response'` event is called before any part of the response body is received,
431 so there is no need to worry about racing to catch the first part of the
432 body. As long as a listener for `'data'` is added during the `'response'`
433 event, the entire body will be caught.
437 request.on('response', function (response) {
438 response.on('data', function (chunk) {
439 console.log('BODY: ' + chunk);
443 // Bad - misses all or part of the body
444 request.on('response', function (response) {
445 setTimeout(function () {
446 response.on('data', function (chunk) {
447 console.log('BODY: ' + chunk);
452 This is a `Writable Stream`.
454 This is an `EventEmitter` with the following events:
458 `function (response) { }`
460 Emitted when a response is received to this request. This event is emitted only once. The
461 `response` argument will be an instance of `http.ClientResponse`.
464 ### request.write(chunk, encoding='utf8')
466 Sends a chunk of the body. By calling this method
467 many times, the user can stream a request body to a
468 server--in that case it is suggested to use the
469 `['Transfer-Encoding', 'chunked']` header line when
470 creating the request.
472 The `chunk` argument should be an array of integers
475 The `encoding` argument is optional and only
476 applies when `chunk` is a string.
479 ### request.end([data], [encoding])
481 Finishes sending the request. If any parts of the body are
482 unsent, it will flush them to the stream. If the request is
483 chunked, this will send the terminating `'0\r\n\r\n'`.
485 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
486 followed by `request.end()`.
489 ## http.ClientResponse
491 This object is created when making a request with `http.Client`. It is
492 passed to the `'response'` event of the request object.
494 The response implements the `Readable Stream` interface.
498 `function (chunk) {}`
500 Emitted when a piece of the message body is received.
502 Example: A chunk of the body is given as the single
503 argument. The transfer-encoding has been decoded. The
504 body chunk a String. The body encoding is set with
505 `response.setBodyEncoding()`.
511 Emitted exactly once for each message. No arguments. After
512 emitted no other events will be emitted on the response.
514 ### response.statusCode
516 The 3-digit HTTP response status code. E.G. `404`.
518 ### response.httpVersion
520 The HTTP version of the connected-to server. Probably either
522 Also `response.httpVersionMajor` is the first integer and
523 `response.httpVersionMinor` is the second.
527 The response headers object.
529 ### response.trailers
531 The response trailers object. Only populated after the 'end' event.
533 ### response.setEncoding(encoding=null)
535 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
536 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
540 Pauses response from emitting events. Useful to throttle back a download.
542 ### response.resume()
544 Resumes a paused response.
548 A reference to the `http.Client` that this response belongs to.