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 `request` is an instance of `http.ServerRequest` and `response` is
35 an instance of `http.ServerResponse`
37 ### Event: 'connection'
39 `function (stream) { }`
41 When a new TCP stream is established. `stream` is an object of type
42 `net.Stream`. Usually users will not want to access this event. The
43 `stream` can also be accessed at `request.connection`.
47 `function (errno) { }`
49 Emitted when the server closes.
53 `function (request, response) {}`
55 Emitted each time there is request. Note that there may be multiple requests
56 per connection (in the case of keep-alive connections).
58 ### Event: 'checkContinue'
60 `function (request, response) {}`
62 Emitted each time a request with an http Expect: 100-continue is received.
63 If this event isn't listened for, the server will automatically respond
64 with a 100 Continue as appropriate.
66 Handling this event involves calling `response.writeContinue` if the client
67 should continue to send the request body, or generating an appropriate HTTP
68 response (e.g., 400 Bad Request) if the client should not continue to send the
71 Note that when this event is emitted and handled, the `request` event will
76 `function (request, socket, head)`
78 Emitted each time a client requests a http upgrade. If this event isn't
79 listened for, then clients requesting an upgrade will have their connections
82 * `request` is the arguments for the http request, as it is in the request event.
83 * `socket` is the network socket between the server and client.
84 * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
86 After this event is emitted, the request's socket will not have a `data`
87 event listener, meaning you will need to bind to it in order to handle data
88 sent to the server on that socket.
90 ### Event: 'clientError'
92 `function (exception) {}`
94 If a client connection emits an 'error' event - it will forwarded here.
96 ### http.createServer(requestListener)
98 Returns a new web server object.
100 The `requestListener` is a function which is automatically
101 added to the `'request'` event.
103 ### server.listen(port, [hostname], [callback])
105 Begin accepting connections on the specified port and hostname. If the
106 hostname is omitted, the server will accept connections directed to any
107 IPv4 address (`INADDR_ANY`).
109 To listen to a unix socket, supply a filename instead of port and hostname.
111 This function is asynchronous. The last parameter `callback` will be called
112 when the server has been bound to the port.
115 ### server.listen(path, [callback])
117 Start a UNIX socket server listening for connections on the given `path`.
119 This function is asynchronous. The last parameter `callback` will be called
120 when the server has been bound.
125 Stops the server from accepting new connections.
128 ## http.ServerRequest
130 This object is created internally by a HTTP server -- not by
131 the user -- and passed as the first argument to a `'request'` listener.
133 This is an `EventEmitter` with the following events:
137 `function (chunk) { }`
139 Emitted when a piece of the message body is received.
141 Example: A chunk of the body is given as the single
142 argument. The transfer-encoding has been decoded. The
143 body chunk is a string. The body encoding is set with
144 `request.setBodyEncoding()`.
150 Emitted exactly once for each message. No arguments. After
151 emitted no other events will be emitted on the request.
156 The request method as a string. Read only. Example:
162 Request URL string. This contains only the URL that is
163 present in the actual HTTP request. If the request is:
165 GET /status?name=ryan HTTP/1.1\r\n
166 Accept: text/plain\r\n
169 Then `request.url` will be:
173 If you would like to parse the URL into its parts, you can use
174 `require('url').parse(request.url)`. Example:
176 node> require('url').parse('/status?name=ryan')
177 { href: '/status?name=ryan',
178 search: '?name=ryan',
180 pathname: '/status' }
182 If you would like to extract the params from the query string,
183 you can use the `require('querystring').parse` function, or pass
184 `true` as the second argument to `require('url').parse`. Example:
186 node> require('url').parse('/status?name=ryan', true)
187 { href: '/status?name=ryan',
188 search: '?name=ryan',
189 query: { name: 'ryan' },
190 pathname: '/status' }
200 Read only; HTTP trailers (if present). Only populated after the 'end' event.
202 ### request.httpVersion
204 The HTTP protocol version as a string. Read only. Examples:
206 Also `request.httpVersionMajor` is the first integer and
207 `request.httpVersionMinor` is the second.
210 ### request.setEncoding(encoding=null)
212 Set the encoding for the request body. Either `'utf8'` or `'binary'`. Defaults
213 to `null`, which means that the `'data'` event will emit a `Buffer` object..
218 Pauses request from emitting events. Useful to throttle back an upload.
223 Resumes a paused request.
225 ### request.connection
227 The `net.Stream` object associated with the connection.
230 With HTTPS support, use request.connection.verifyPeer() and
231 request.connection.getPeerCertificate() to obtain the client's
232 authentication details.
236 ## http.ServerResponse
238 This object is created internally by a HTTP server--not by the user. It is
239 passed as the second parameter to the `'request'` event. It is a `Writable Stream`.
241 ### response.writeContinue()
243 Sends a HTTP/1.1 100 Continue message to the client, indicating that
244 the request body should be sent. See the the `checkContinue` event on
247 ### response.writeHead(statusCode, [reasonPhrase], [headers])
249 Sends a response header to the request. The status code is a 3-digit HTTP
250 status code, like `404`. The last argument, `headers`, are the response headers.
251 Optionally one can give a human-readable `reasonPhrase` as the second
256 var body = 'hello world';
257 response.writeHead(200, {
258 'Content-Length': body.length,
259 'Content-Type': 'text/plain' });
261 This method must only be called once on a message and it must
262 be called before `response.end()` is called.
264 ### response.write(chunk, encoding='utf8')
266 This method must be called after `writeHead` was
267 called. It sends a chunk of the response body. This method may
268 be called multiple times to provide successive parts of the body.
270 `chunk` can be a string or a buffer. If `chunk` is a string,
271 the second parameter specifies how to encode it into a byte stream.
272 By default the `encoding` is `'utf8'`.
274 **Note**: This is the raw HTTP body and has nothing to do with
275 higher-level multi-part body encodings that may be used.
277 The first time `response.write()` is called, it will send the buffered
278 header information and the first body to the client. The second time
279 `response.write()` is called, Node assumes you're going to be streaming
280 data, and sends that separately. That is, the response is buffered up to the
283 ### response.addTrailers(headers)
285 This method adds HTTP trailing headers (a header but at the end of the
286 message) to the response.
288 Trailers will **only** be emitted if chunked encoding is used for the
289 response; if it is not (e.g., if the request was HTTP/1.0), they will
290 be silently discarded.
292 Note that HTTP requires the `Trailer` header to be sent if you intend to
293 emit trailers, with a list of the header fields in its value. E.g.,
295 response.writeHead(200, { 'Content-Type': 'text/plain',
296 'Trailer': 'TraceInfo' });
297 response.write(fileData);
298 response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
302 ### response.end([data], [encoding])
304 This method signals to the server that all of the response headers and body
305 has been sent; that server should consider this message complete.
306 The method, `response.end()`, MUST be called on each
309 If `data` is specified, it is equivalent to calling `response.write(data, encoding)`
310 followed by `response.end()`.
313 ## http.request(options, callback)
315 Node maintains several connections per server to make HTTP requests.
316 This function allows one to transparently issue requests.
320 - `host`: A domain name or IP address of the server to issue the request to.
321 - `port`: Port of remote server.
322 - `method`: A string specifing the HTTP request method. Possible values:
323 `'GET'` (default), `'POST'`, `'PUT'`, and `'DELETE'`.
324 - `path`: Request path. Should include query string and fragments if any.
325 E.G. `'/index.html?page=12'`
326 - `headers`: An object containing request headers.
328 `http.request()` returns an instance of the `http.ClientRequest`
329 class. The `ClientRequest` instance is a writable stream. If one needs to
330 upload a file with a POST request, then write to the `ClientRequest` object.
335 host: 'www.google.com',
341 var req = http.request(options, function(res) {
342 console.log('STATUS: ' + res.statusCode);
343 console.log('HEADERS: ' + JSON.stringify(res.headers));
344 res.setEncoding('utf8');
345 res.on('data', function (chunk) {
346 console.log('BODY: ' + chunk);
350 // write data to request body
355 Note that in the example `req.end()` was called. With `http.request()` one
356 must always call `req.end()` to signify that you're done with the request -
357 even if there is no data being written to the request body.
359 If any error is encountered during the request (be that with DNS resolution,
360 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
361 on the returned request object.
363 There are a few special headers that should be noted.
365 * Sending a 'Connection: keep-alive' will notify Node that the connection to
366 the server should be persisted until the next request.
368 * Sending a 'Content-length' header will disable the default chunked encoding.
370 * Sending an 'Expect' header will immediately send the request headers.
371 Usually, when sending 'Expect: 100-continue', you should both set a timeout
372 and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
375 ## http.get(options, callback)
377 Since most requests are GET requests without bodies, Node provides this
378 convience method. The only difference between this method and `http.request()` is
379 that it sets the method to GET and calls `req.end()` automatically.
384 host: 'www.google.com',
389 http.get(options, function(res) {
390 console.log("Got response: " + res.statusCode);
391 }).on('error', function(e) {
392 console.log("Got error: " + e.message);
397 ## http.getAgent(host, port)
399 `http.request()` uses a special `Agent` for managing multiple connections to
400 an HTTP server. Normally `Agent` instances should not be exposed to user
401 code, however in certain situations it's useful to check the status of the
402 agent. The `http.getAgent()` function allows you to access the agents.
406 `function (request, socket, head)`
408 Emitted each time a server responds to a request with an upgrade. If this event
409 isn't being listened for, clients receiving an upgrade header will have their
412 See the description of the `upgrade` event for `http.Server` for further details.
414 ### Event: 'continue'
418 Emitted when the server sends a '100 Continue' HTTP response, usually because
419 the request contained 'Expect: 100-continue'. This is an instruction that
420 the client should send the request body.
424 By default set to 5. Determines how many concurrent sockets the agent can have open.
428 An array of sockets currently inuse by the Agent. Do not modify.
432 A queue of requests waiting to be sent to sockets.
436 ## http.ClientRequest
438 This object is created internally and returned from `http.request()`. It
439 represents an _in-progress_ request whose header has already been sent.
441 To get the response, add a listener for `'response'` to the request object.
442 `'response'` will be emitted from the request object when the response
443 headers have been received. The `'response'` event is executed with one
444 argument which is an instance of `http.ClientResponse`.
446 During the `'response'` event, one can add listeners to the
447 response object; particularly to listen for the `'data'` event. Note that
448 the `'response'` event is called before any part of the response body is received,
449 so there is no need to worry about racing to catch the first part of the
450 body. As long as a listener for `'data'` is added during the `'response'`
451 event, the entire body will be caught.
455 request.on('response', function (response) {
456 response.on('data', function (chunk) {
457 console.log('BODY: ' + chunk);
461 // Bad - misses all or part of the body
462 request.on('response', function (response) {
463 setTimeout(function () {
464 response.on('data', function (chunk) {
465 console.log('BODY: ' + chunk);
470 This is a `Writable Stream`.
472 This is an `EventEmitter` with the following events:
476 `function (response) { }`
478 Emitted when a response is received to this request. This event is emitted only once. The
479 `response` argument will be an instance of `http.ClientResponse`.
482 ### request.write(chunk, encoding='utf8')
484 Sends a chunk of the body. By calling this method
485 many times, the user can stream a request body to a
486 server--in that case it is suggested to use the
487 `['Transfer-Encoding', 'chunked']` header line when
488 creating the request.
490 The `chunk` argument should be an array of integers
493 The `encoding` argument is optional and only
494 applies when `chunk` is a string.
497 ### request.end([data], [encoding])
499 Finishes sending the request. If any parts of the body are
500 unsent, it will flush them to the stream. If the request is
501 chunked, this will send the terminating `'0\r\n\r\n'`.
503 If `data` is specified, it is equivalent to calling `request.write(data, encoding)`
504 followed by `request.end()`.
508 Aborts a request. (New since v0.3.8.)
511 ## http.ClientResponse
513 This object is created when making a request with `http.request()`. It is
514 passed to the `'response'` event of the request object.
516 The response implements the `Readable Stream` interface.
520 `function (chunk) {}`
522 Emitted when a piece of the message body is received.
529 Emitted exactly once for each message. No arguments. After
530 emitted no other events will be emitted on the response.
532 ### response.statusCode
534 The 3-digit HTTP response status code. E.G. `404`.
536 ### response.httpVersion
538 The HTTP version of the connected-to server. Probably either
540 Also `response.httpVersionMajor` is the first integer and
541 `response.httpVersionMinor` is the second.
545 The response headers object.
547 ### response.trailers
549 The response trailers object. Only populated after the 'end' event.
551 ### response.setEncoding(encoding=null)
553 Set the encoding for the response body. Either `'utf8'`, `'ascii'`, or `'base64'`.
554 Defaults to `null`, which means that the `'data'` event will emit a `Buffer` object..
558 Pauses response from emitting events. Useful to throttle back a download.
560 ### response.resume()
562 Resumes a paused response.