5 To use the HTTP server and client one must `require('http')`.
7 The HTTP interfaces in Node.js are designed to support many features
8 of the protocol which have been traditionally difficult to use.
9 In particular, large, possibly chunk-encoded, messages. The interface is
10 careful to never buffer entire requests or responses--the
11 user is able to stream data.
13 HTTP message headers are represented by an object like this:
15 { 'content-length': '123',
16 'content-type': 'text/plain',
17 'connection': 'keep-alive',
21 Keys are lowercased. Values are not modified.
23 In order to support the full spectrum of possible HTTP applications, Node.js's
24 HTTP API is very low-level. It deals with stream handling and message
25 parsing only. It parses a message into headers and body but it does not
26 parse the actual headers or the body.
28 See [`message.headers`][] for details on how duplicate headers are handled.
30 The raw headers as they were received are retained in the `rawHeaders`
31 property, which is an array of `[key, value, key2, value2, ...]`. For
32 example, the previous message header object might have a `rawHeaders`
33 list like the following:
35 [ 'ConTent-Length', '123456',
36 'content-LENGTH', '123',
37 'content-type', 'text/plain',
38 'CONNECTION', 'keep-alive',
44 The HTTP Agent is used for pooling sockets used in HTTP client
47 The HTTP Agent also defaults client requests to using
48 Connection:keep-alive. If no pending HTTP requests are waiting on a
49 socket to become free the socket is closed. This means that Node.js's
50 pool has the benefit of keep-alive when under load but still does not
51 require developers to manually close the HTTP clients using
54 If you opt into using HTTP KeepAlive, you can create an Agent object
55 with that flag set to `true`. (See the [constructor options][] below.)
56 Then, the Agent will keep unused sockets in a pool for later use. They
57 will be explicitly marked so as to not keep the Node.js process running.
58 However, it is still a good idea to explicitly [`destroy()`][] KeepAlive
59 agents when they are no longer in use, so that the Sockets will be shut
62 Sockets are removed from the agent's pool when the socket emits either
63 a `'close'` event or a special `'agentRemove'` event. This means that if
64 you intend to keep one HTTP request open for a long time and don't
65 want it to stay in the pool you can do something along the lines of:
67 http.get(options, (res) => {
69 }).on('socket', (socket) => {
70 socket.emit('agentRemove');
73 Alternatively, you could just opt out of pooling entirely using
77 hostname: 'localhost',
80 agent: false // create a new agent just for this one request
82 // Do stuff with response
85 ### new Agent([options])
87 * `options` {Object} Set of configurable options to set on the agent.
88 Can have the following fields:
89 * `keepAlive` {Boolean} Keep sockets around in a pool to be used by
90 other requests in the future. Default = `false`
91 * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often
92 to send TCP KeepAlive packets over sockets being kept alive.
93 Default = `1000`. Only relevant if `keepAlive` is set to `true`.
94 * `maxSockets` {Number} Maximum number of sockets to allow per
95 host. Default = `Infinity`.
96 * `maxFreeSockets` {Number} Maximum number of sockets to leave open
97 in a free state. Only relevant if `keepAlive` is set to `true`.
100 The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
101 of these values set to their respective defaults.
103 To configure any of them, you must create your own [`http.Agent`][] object.
106 const http = require('http');
107 var keepAliveAgent = new http.Agent({ keepAlive: true });
108 options.agent = keepAliveAgent;
109 http.request(options, onResponseCallback);
114 Destroy any sockets that are currently in use by the agent.
116 It is usually not necessary to do this. However, if you are using an
117 agent with KeepAlive enabled, then it is best to explicitly shut down
118 the agent when you know that it will no longer be used. Otherwise,
119 sockets may hang open for quite a long time before the server
122 ### agent.freeSockets
124 An object which contains arrays of sockets currently awaiting use by
125 the Agent when HTTP KeepAlive is used. Do not modify.
127 ### agent.getName(options)
129 Get a unique name for a set of request options, to determine whether a
130 connection can be reused. In the http agent, this returns
131 `host:port:localAddress`. In the https agent, the name includes the
132 CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
135 ### agent.maxFreeSockets
137 By default set to 256. For Agents supporting HTTP KeepAlive, this
138 sets the maximum number of sockets that will be left open in the free
143 By default set to Infinity. Determines how many concurrent sockets the agent
144 can have open per origin. Origin is either a 'host:port' or
145 'host:port:localAddress' combination.
149 An object which contains queues of requests that have not yet been assigned to
150 sockets. Do not modify.
154 An object which contains arrays of sockets currently in use by the
155 Agent. Do not modify.
157 ## Class: http.ClientRequest
159 This object is created internally and returned from [`http.request()`][]. It
160 represents an _in-progress_ request whose header has already been queued. The
161 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
162 `removeHeader(name)` API. The actual header will be sent along with the first
163 data chunk or when closing the connection.
165 To get the response, add a listener for `'response'` to the request object.
166 `'response'` will be emitted from the request object when the response
167 headers have been received. The `'response'` event is executed with one
168 argument which is an instance of [`http.IncomingMessage`][].
170 During the `'response'` event, one can add listeners to the
171 response object; particularly to listen for the `'data'` event.
173 If no `'response'` handler is added, then the response will be
174 entirely discarded. However, if you add a `'response'` event handler,
175 then you **must** consume the data from the response object, either by
176 calling `response.read()` whenever there is a `'readable'` event, or
177 by adding a `'data'` handler, or by calling the `.resume()` method.
178 Until the data is consumed, the `'end'` event will not fire. Also, until
179 the data is read it will consume memory that can eventually lead to a
180 'process out of memory' error.
182 Note: Node.js does not check whether Content-Length and the length of the body
183 which has been transmitted are equal or not.
185 The request implements the [Writable Stream][] interface. This is an
186 [`EventEmitter`][] with the following events:
192 Emitted when the request has been aborted by the client. This event is only
193 emitted on the first call to `abort()`.
197 `function (response, socket, head) { }`
199 Emitted each time a server responds to a request with a `CONNECT` method. If this
200 event isn't being listened for, clients receiving a `CONNECT` method will have
201 their connections closed.
203 A client server pair that show you how to listen for the `'connect'` event.
205 const http = require('http');
206 const net = require('net');
207 const url = require('url');
209 // Create an HTTP tunneling proxy
210 var proxy = http.createServer( (req, res) => {
211 res.writeHead(200, {'Content-Type': 'text/plain'});
214 proxy.on('connect', (req, cltSocket, head) => {
215 // connect to an origin server
216 var srvUrl = url.parse(`http://${req.url}`);
217 var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
218 cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
219 'Proxy-agent: Node.js-Proxy\r\n' +
221 srvSocket.write(head);
222 srvSocket.pipe(cltSocket);
223 cltSocket.pipe(srvSocket);
227 // now that proxy is running
228 proxy.listen(1337, '127.0.0.1', () => {
230 // make a request to a tunneling proxy
233 hostname: '127.0.0.1',
235 path: 'www.google.com:80'
238 var req = http.request(options);
241 req.on('connect', (res, socket, head) => {
242 console.log('got connected!');
244 // make a request over an HTTP tunnel
245 socket.write('GET / HTTP/1.1\r\n' +
246 'Host: www.google.com:80\r\n' +
247 'Connection: close\r\n' +
249 socket.on('data', (chunk) => {
250 console.log(chunk.toString());
252 socket.on('end', () => {
258 ### Event: 'continue'
262 Emitted when the server sends a '100 Continue' HTTP response, usually because
263 the request contained 'Expect: 100-continue'. This is an instruction that
264 the client should send the request body.
266 ### Event: 'response'
268 `function (response) { }`
270 Emitted when a response is received to this request. This event is emitted only
271 once. The `response` argument will be an instance of [`http.IncomingMessage`][].
275 - `host`: A domain name or IP address of the server to issue the request to.
276 - `port`: Port of remote server.
277 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
281 `function (socket) { }`
283 Emitted after a socket is assigned to this request.
287 `function (response, socket, head) { }`
289 Emitted each time a server responds to a request with an upgrade. If this
290 event isn't being listened for, clients receiving an upgrade header will have
291 their connections closed.
293 A client server pair that show you how to listen for the `'upgrade'` event.
295 const http = require('http');
297 // Create an HTTP server
298 var srv = http.createServer( (req, res) => {
299 res.writeHead(200, {'Content-Type': 'text/plain'});
302 srv.on('upgrade', (req, socket, head) => {
303 socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
304 'Upgrade: WebSocket\r\n' +
305 'Connection: Upgrade\r\n' +
308 socket.pipe(socket); // echo back
311 // now that server is running
312 srv.listen(1337, '127.0.0.1', () => {
317 hostname: '127.0.0.1',
319 'Connection': 'Upgrade',
320 'Upgrade': 'websocket'
324 var req = http.request(options);
327 req.on('upgrade', (res, socket, upgradeHead) => {
328 console.log('got upgraded!');
336 Marks the request as aborting. Calling this will cause remaining data
337 in the response to be dropped and the socket to be destroyed.
339 ### request.end([data][, encoding][, callback])
341 Finishes sending the request. If any parts of the body are
342 unsent, it will flush them to the stream. If the request is
343 chunked, this will send the terminating `'0\r\n\r\n'`.
345 If `data` is specified, it is equivalent to calling
346 [`response.write(data, encoding)`][] followed by `request.end(callback)`.
348 If `callback` is specified, it will be called when the request stream
351 ### request.flushHeaders()
353 Flush the request headers.
355 For efficiency reasons, Node.js normally buffers the request headers until you
356 call `request.end()` or write the first chunk of request data. It then tries
357 hard to pack the request headers and data into a single TCP packet.
359 That's usually what you want (it saves a TCP round-trip) but not when the first
360 data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass
361 the optimization and kickstart the request.
363 ### request.setNoDelay([noDelay])
365 Once a socket is assigned to this request and is connected
366 [`socket.setNoDelay()`][] will be called.
368 ### request.setSocketKeepAlive([enable][, initialDelay])
370 Once a socket is assigned to this request and is connected
371 [`socket.setKeepAlive()`][] will be called.
373 ### request.setTimeout(timeout[, callback])
375 Once a socket is assigned to this request and is connected
376 [`socket.setTimeout()`][] will be called.
378 * `timeout` {Number} Milliseconds before a request is considered to be timed out.
379 * `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.
381 ### request.write(chunk[, encoding][, callback])
383 Sends a chunk of the body. By calling this method
384 many times, the user can stream a request body to a
385 server--in that case it is suggested to use the
386 `['Transfer-Encoding', 'chunked']` header line when
387 creating the request.
389 The `chunk` argument should be a [`Buffer`][] or a string.
391 The `encoding` argument is optional and only applies when `chunk` is a string.
392 Defaults to `'utf8'`.
394 The `callback` argument is optional and will be called when this chunk of data
399 ## Class: http.Server
401 This class inherits from [`net.Server`][] and has the following additional events:
403 ### Event: 'checkContinue'
405 `function (request, response) { }`
407 Emitted each time a request with an http Expect: 100-continue is received.
408 If this event isn't listened for, the server will automatically respond
409 with a 100 Continue as appropriate.
411 Handling this event involves calling [`response.writeContinue()`][] if the client
412 should continue to send the request body, or generating an appropriate HTTP
413 response (e.g., 400 Bad Request) if the client should not continue to send the
416 Note that when this event is emitted and handled, the `'request'` event will
419 ### Event: 'clientError'
421 `function (exception, socket) { }`
423 If a client connection emits an `'error'` event, it will be forwarded here.
425 `socket` is the [`net.Socket`][] object that the error originated from.
431 Emitted when the server closes.
435 `function (request, socket, head) { }`
437 Emitted each time a client requests a http `CONNECT` method. If this event isn't
438 listened for, then clients requesting a `CONNECT` method will have their
441 * `request` is the arguments for the http request, as it is in the request
443 * `socket` is the network socket between the server and client.
444 * `head` is an instance of Buffer, the first packet of the tunneling stream,
447 After this event is emitted, the request's socket will not have a `'data'`
448 event listener, meaning you will need to bind to it in order to handle data
449 sent to the server on that socket.
451 ### Event: 'connection'
453 `function (socket) { }`
455 When a new TCP stream is established. `socket` is an object of type
456 [`net.Socket`][]. Usually users will not want to access this event. In
457 particular, the socket will not emit `'readable'` events because of how
458 the protocol parser attaches to the socket. The `socket` can also be
459 accessed at `request.connection`.
463 `function (request, response) { }`
465 Emitted each time there is a request. Note that there may be multiple requests
466 per connection (in the case of keep-alive connections).
467 `request` is an instance of [`http.IncomingMessage`][] and `response` is
468 an instance of [`http.ServerResponse`][].
472 `function (request, socket, head) { }`
474 Emitted each time a client requests a http upgrade. If this event isn't
475 listened for, then clients requesting an upgrade will have their connections
478 * `request` is the arguments for the http request, as it is in the request
480 * `socket` is the network socket between the server and client.
481 * `head` is an instance of Buffer, the first packet of the upgraded stream,
484 After this event is emitted, the request's socket will not have a `'data'`
485 event listener, meaning you will need to bind to it in order to handle data
486 sent to the server on that socket.
488 ### server.close([callback])
490 Stops the server from accepting new connections. See [`net.Server.close()`][].
492 ### server.listen(handle[, callback])
495 * `callback` {Function}
497 The `handle` object can be set to either a server or socket (anything
498 with an underlying `_handle` member), or a `{fd: <n>}` object.
500 This will cause the server to accept connections on the specified
501 handle, but it is presumed that the file descriptor or handle has
502 already been bound to a port or domain socket.
504 Listening on a file descriptor is not supported on Windows.
506 This function is asynchronous. The last parameter `callback` will be added as
507 a listener for the `'listening'` event. See also [`net.Server.listen()`][].
511 ### server.listen(path[, callback])
513 Start a UNIX socket server listening for connections on the given `path`.
515 This function is asynchronous. The last parameter `callback` will be added as
516 a listener for the `'listening'` event. See also [`net.Server.listen(path)`][].
518 ### server.listen(port[, hostname][, backlog][, callback])
520 Begin accepting connections on the specified `port` and `hostname`. If the
521 `hostname` is omitted, the server will accept connections on any IPv6 address
522 (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
523 port value of zero will assign a random port.
525 To listen to a unix socket, supply a filename instead of port and hostname.
527 Backlog is the maximum length of the queue of pending connections.
528 The actual length will be determined by your OS through sysctl settings such as
529 `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
530 parameter is 511 (not 512).
532 This function is asynchronous. The last parameter `callback` will be added as
533 a listener for the `'listening'` event. See also [`net.Server.listen(port)`][].
535 ### server.maxHeadersCount
537 Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
538 no limit will be applied.
540 ### server.setTimeout(msecs, callback)
543 * `callback` {Function}
545 Sets the timeout value for sockets, and emits a `'timeout'` event on
546 the Server object, passing the socket as an argument, if a timeout
549 If there is a `'timeout'` event listener on the Server object, then it
550 will be called with the timed-out socket as an argument.
552 By default, the Server's timeout value is 2 minutes, and sockets are
553 destroyed automatically if they time out. However, if you assign a
554 callback to the Server's `'timeout'` event, then you are responsible
555 for handling socket timeouts.
561 * {Number} Default = 120000 (2 minutes)
563 The number of milliseconds of inactivity before a socket is presumed
566 Note that the socket timeout logic is set up on connection, so
567 changing this value only affects *new* connections to the server, not
568 any existing connections.
570 Set to 0 to disable any kind of automatic timeout behavior on incoming
573 ## Class: http.ServerResponse
575 This object is created internally by a HTTP server--not by the user. It is
576 passed as the second parameter to the `'request'` event.
578 The response implements the [Writable Stream][] interface. This is an
579 [`EventEmitter`][] with the following events:
585 Indicates that the underlying connection was terminated before
586 [`response.end()`][] was called or able to flush.
592 Emitted when the response has been sent. More specifically, this event is
593 emitted when the last segment of the response headers and body have been
594 handed off to the operating system for transmission over the network. It
595 does not imply that the client has received anything yet.
597 After this event, no more events will be emitted on the response object.
599 ### response.addTrailers(headers)
601 This method adds HTTP trailing headers (a header but at the end of the
602 message) to the response.
604 Trailers will **only** be emitted if chunked encoding is used for the
605 response; if it is not (e.g., if the request was HTTP/1.0), they will
606 be silently discarded.
608 Note that HTTP requires the `Trailer` header to be sent if you intend to
609 emit trailers, with a list of the header fields in its value. E.g.,
611 response.writeHead(200, { 'Content-Type': 'text/plain',
612 'Trailer': 'Content-MD5' });
613 response.write(fileData);
614 response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
617 Attempting to set a header field name or value that contains invalid characters
618 will result in a [`TypeError`][] being thrown.
620 ### response.end([data][, encoding][, callback])
622 This method signals to the server that all of the response headers and body
623 have been sent; that server should consider this message complete.
624 The method, `response.end()`, MUST be called on each response.
626 If `data` is specified, it is equivalent to calling
627 [`response.write(data, encoding)`][] followed by `response.end(callback)`.
629 If `callback` is specified, it will be called when the response stream
632 ### response.finished
634 Boolean value that indicates whether the response has completed. Starts
635 as `false`. After [`response.end()`][] executes, the value will be `true`.
637 ### response.getHeader(name)
639 Reads out a header that's already been queued but not sent to the client. Note
640 that the name is case insensitive. This can only be called before headers get
645 var contentType = response.getHeader('content-type');
647 ### response.headersSent
649 Boolean (read-only). True if headers were sent, false otherwise.
651 ### response.removeHeader(name)
653 Removes a header that's queued for implicit sending.
657 response.removeHeader('Content-Encoding');
659 ### response.sendDate
661 When true, the Date header will be automatically generated and sent in
662 the response if it is not already present in the headers. Defaults to true.
664 This should only be disabled for testing; HTTP requires the Date header
667 ### response.setHeader(name, value)
669 Sets a single header value for implicit headers. If this header already exists
670 in the to-be-sent headers, its value will be replaced. Use an array of strings
671 here if you need to send multiple headers with the same name.
675 response.setHeader('Content-Type', 'text/html');
679 response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
681 Attempting to set a header field name or value that contains invalid characters
682 will result in a [`TypeError`][] being thrown.
684 ### response.setTimeout(msecs, callback)
687 * `callback` {Function}
689 Sets the Socket's timeout value to `msecs`. If a callback is
690 provided, then it is added as a listener on the `'timeout'` event on
693 If no `'timeout'` listener is added to the request, the response, or
694 the server, then sockets are destroyed when they time out. If you
695 assign a handler on the request, the response, or the server's
696 `'timeout'` events, then it is your responsibility to handle timed out
701 ### response.statusCode
703 When using implicit headers (not calling [`response.writeHead()`][] explicitly),
704 this property controls the status code that will be sent to the client when
705 the headers get flushed.
709 response.statusCode = 404;
711 After response header was sent to the client, this property indicates the
712 status code which was sent out.
714 ### response.statusMessage
716 When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property
717 controls the status message that will be sent to the client when the headers get
718 flushed. If this is left as `undefined` then the standard message for the status
723 response.statusMessage = 'Not found';
725 After response header was sent to the client, this property indicates the
726 status message which was sent out.
728 ### response.write(chunk[, encoding][, callback])
730 If this method is called and [`response.writeHead()`][] has not been called,
731 it will switch to implicit header mode and flush the implicit headers.
733 This sends a chunk of the response body. This method may
734 be called multiple times to provide successive parts of the body.
736 `chunk` can be a string or a buffer. If `chunk` is a string,
737 the second parameter specifies how to encode it into a byte stream.
738 By default the `encoding` is `'utf8'`. The last parameter `callback`
739 will be called when this chunk of data is flushed.
741 **Note**: This is the raw HTTP body and has nothing to do with
742 higher-level multi-part body encodings that may be used.
744 The first time [`response.write()`][] is called, it will send the buffered
745 header information and the first body to the client. The second time
746 [`response.write()`][] is called, Node.js assumes you're going to be streaming
747 data, and sends that separately. That is, the response is buffered up to the
750 Returns `true` if the entire data was flushed successfully to the kernel
751 buffer. Returns `false` if all or part of the data was queued in user memory.
752 `'drain'` will be emitted when the buffer is free again.
754 ### response.writeContinue()
756 Sends a HTTP/1.1 100 Continue message to the client, indicating that
757 the request body should be sent. See the [`'checkContinue'`][] event on `Server`.
759 ### response.writeHead(statusCode[, statusMessage][, headers])
761 Sends a response header to the request. The status code is a 3-digit HTTP
762 status code, like `404`. The last argument, `headers`, are the response headers.
763 Optionally one can give a human-readable `statusMessage` as the second
768 var body = 'hello world';
769 response.writeHead(200, {
770 'Content-Length': body.length,
771 'Content-Type': 'text/plain' });
773 This method must only be called once on a message and it must
774 be called before [`response.end()`][] is called.
776 If you call [`response.write()`][] or [`response.end()`][] before calling this,
777 the implicit/mutable headers will be calculated and call this function for you.
779 Note that Content-Length is given in bytes not characters. The above example
780 works because the string `'hello world'` contains only single byte characters.
781 If the body contains higher coded characters then `Buffer.byteLength()`
782 should be used to determine the number of bytes in a given encoding.
783 And Node.js does not check whether Content-Length and the length of the body
784 which has been transmitted are equal or not.
786 Attempting to set a header field name or value that contains invalid characters
787 will result in a [`TypeError`][] being thrown.
789 ## Class: http.IncomingMessage
791 An `IncomingMessage` object is created by [`http.Server`][] or
792 [`http.ClientRequest`][] and passed as the first argument to the `'request'`
793 and `'response'` event respectively. It may be used to access response status,
796 It implements the [Readable Stream][] interface, as well as the
797 following additional events, methods, and properties.
803 Indicates that the underlying connection was closed.
804 Just like `'end'`, this event occurs only once per response.
808 The request/response headers object.
810 Key-value pairs of header names and values. Header names are lower-cased.
813 // Prints something like:
815 // { 'user-agent': 'curl/7.22.0',
816 // host: '127.0.0.1:8000',
818 console.log(request.headers);
820 Duplicates in raw headers are handled in the following ways, depending on the
823 * Duplicates of `age`, `authorization`, `content-length`, `content-type`,
824 `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
825 `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
826 `retry-after`, or `user-agent` are discarded.
827 * `set-cookie` is always an array. Duplicates are added to the array.
828 * For all other headers, the values are joined together with ', '.
830 ### message.httpVersion
832 In case of server request, the HTTP version sent by the client. In the case of
833 client response, the HTTP version of the connected-to server.
834 Probably either `'1.1'` or `'1.0'`.
836 Also `response.httpVersionMajor` is the first integer and
837 `response.httpVersionMinor` is the second.
841 **Only valid for request obtained from [`http.Server`][].**
843 The request method as a string. Read only. Example:
846 ### message.rawHeaders
848 The raw request/response headers list exactly as they were received.
850 Note that the keys and values are in the same list. It is *not* a
851 list of tuples. So, the even-numbered offsets are key values, and the
852 odd-numbered offsets are the associated values.
854 Header names are not lowercased, and duplicates are not merged.
856 // Prints something like:
859 // 'this is invalid because there can be only one',
866 console.log(request.rawHeaders);
868 ### message.rawTrailers
870 The raw request/response trailer keys and values exactly as they were
871 received. Only populated at the `'end'` event.
873 ### message.setTimeout(msecs, callback)
876 * `callback` {Function}
878 Calls `message.connection.setTimeout(msecs, callback)`.
882 ### message.statusCode
884 **Only valid for response obtained from [`http.ClientRequest`][].**
886 The 3-digit HTTP response status code. E.G. `404`.
888 ### message.statusMessage
890 **Only valid for response obtained from [`http.ClientRequest`][].**
892 The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
896 The [`net.Socket`][] object associated with the connection.
898 With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
899 client's authentication details.
903 The request/response trailers object. Only populated at the `'end'` event.
907 **Only valid for request obtained from [`http.Server`][].**
909 Request URL string. This contains only the URL that is
910 present in the actual HTTP request. If the request is:
912 GET /status?name=ryan HTTP/1.1\r\n
913 Accept: text/plain\r\n
916 Then `request.url` will be:
920 If you would like to parse the URL into its parts, you can use
921 `require('url').parse(request.url)`. Example:
923 node> require('url').parse('/status?name=ryan')
924 { href: '/status?name=ryan',
925 search: '?name=ryan',
927 pathname: '/status' }
929 If you would like to extract the params from the query string,
930 you can use the `require('querystring').parse` function, or pass
931 `true` as the second argument to `require('url').parse`. Example:
933 node> require('url').parse('/status?name=ryan', true)
934 { href: '/status?name=ryan',
935 search: '?name=ryan',
936 query: { name: 'ryan' },
937 pathname: '/status' }
943 A list of the HTTP methods that are supported by the parser.
949 A collection of all the standard HTTP response status codes, and the
950 short description of each. For example, `http.STATUS_CODES[404] === 'Not
953 ## http.createClient([port][, host])
955 Stability: 0 - Deprecated: Use [`http.request()`][] instead.
957 Constructs a new HTTP client. `port` and `host` refer to the server to be
960 ## http.createServer([requestListener])
962 Returns a new instance of [`http.Server`][].
964 The `requestListener` is a function which is automatically
965 added to the `'request'` event.
967 ## http.get(options[, callback])
969 Since most requests are GET requests without bodies, Node.js provides this
970 convenience method. The only difference between this method and [`http.request()`][]
971 is that it sets the method to GET and calls `req.end()` automatically.
975 http.get('http://www.google.com/index.html', (res) => {
976 console.log(`Got response: ${res.statusCode}`);
977 // consume response body
979 }).on('error', (e) => {
980 console.log(`Got error: ${e.message}`);
985 Global instance of Agent which is used as the default for all http client
988 ## http.request(options[, callback])
990 Node.js maintains several connections per server to make HTTP requests.
991 This function allows one to transparently issue requests.
993 `options` can be an object or a string. If `options` is a string, it is
994 automatically parsed with [`url.parse()`][].
998 - `protocol`: Protocol to use. Defaults to `'http:'`.
999 - `host`: A domain name or IP address of the server to issue the request to.
1000 Defaults to `'localhost'`.
1001 - `hostname`: Alias for `host`. To support [`url.parse()`][] `hostname` is
1002 preferred over `host`.
1003 - `family`: IP address family to use when resolving `host` and `hostname`.
1004 Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be
1006 - `port`: Port of remote server. Defaults to 80.
1007 - `localAddress`: Local interface to bind for network connections.
1008 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath).
1009 - `method`: A string specifying the HTTP request method. Defaults to `'GET'`.
1010 - `path`: Request path. Defaults to `'/'`. Should include query string if any.
1011 E.G. `'/index.html?page=12'`. An exception is thrown when the request path
1012 contains illegal characters. Currently, only spaces are rejected but that
1013 may change in the future.
1014 - `headers`: An object containing request headers.
1015 - `auth`: Basic authentication i.e. `'user:password'` to compute an
1016 Authorization header.
1017 - `agent`: Controls [`Agent`][] behavior. When an Agent is used request will
1018 default to `Connection: keep-alive`. Possible values:
1019 - `undefined` (default): use [`http.globalAgent`][] for this host and port.
1020 - `Agent` object: explicitly use the passed in `Agent`.
1021 - `false`: opts out of connection pooling with an Agent, defaults request to
1022 `Connection: close`.
1024 The optional `callback` parameter will be added as a one time listener for
1025 the `'response'` event.
1027 `http.request()` returns an instance of the [`http.ClientRequest`][]
1028 class. The `ClientRequest` instance is a writable stream. If one needs to
1029 upload a file with a POST request, then write to the `ClientRequest` object.
1033 var postData = querystring.stringify({
1034 'msg' : 'Hello World!'
1038 hostname: 'www.google.com',
1043 'Content-Type': 'application/x-www-form-urlencoded',
1044 'Content-Length': postData.length
1048 var req = http.request(options, (res) => {
1049 console.log(`STATUS: ${res.statusCode}`);
1050 console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
1051 res.setEncoding('utf8');
1052 res.on('data', (chunk) => {
1053 console.log(`BODY: ${chunk}`);
1055 res.on('end', () => {
1056 console.log('No more data in response.')
1060 req.on('error', (e) => {
1061 console.log(`problem with request: ${e.message}`);
1064 // write data to request body
1065 req.write(postData);
1068 Note that in the example `req.end()` was called. With `http.request()` one
1069 must always call `req.end()` to signify that you're done with the request -
1070 even if there is no data being written to the request body.
1072 If any error is encountered during the request (be that with DNS resolution,
1073 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
1074 on the returned request object. As with all `'error'` events, if no listeners
1075 are registered the error will be thrown.
1077 There are a few special headers that should be noted.
1079 * Sending a 'Connection: keep-alive' will notify Node.js that the connection to
1080 the server should be persisted until the next request.
1082 * Sending a 'Content-length' header will disable the default chunked encoding.
1084 * Sending an 'Expect' header will immediately send the request headers.
1085 Usually, when sending 'Expect: 100-continue', you should both set a timeout
1086 and listen for the `'continue'` event. See RFC2616 Section 8.2.3 for more
1089 * Sending an Authorization header will override using the `auth` option
1090 to compute basic authentication.
1092 [`'checkContinue'`]: #http_event_checkcontinue
1093 [`'listening'`]: net.html#net_event_listening
1094 [`'response'`]: #http_event_response
1095 [`Agent`]: #http_class_http_agent
1096 [`Buffer`]: buffer.html#buffer_buffer
1097 [`destroy()`]: #http_agent_destroy
1098 [`EventEmitter`]: events.html#events_class_events_eventemitter
1099 [`http.Agent`]: #http_class_http_agent
1100 [`http.ClientRequest`]: #http_class_http_clientrequest
1101 [`http.globalAgent`]: #http_http_globalagent
1102 [`http.IncomingMessage`]: #http_http_incomingmessage
1103 [`http.request()`]: #http_http_request_options_callback
1104 [`http.Server`]: #http_class_http_server
1105 [`http.ServerResponse`]: #http_class_http_serverresponse
1106 [`message.headers`]: #http_message_headers
1107 [`net.Server`]: net.html#net_class_net_server
1108 [`net.Server.close()`]: net.html#net_server_close_callback
1109 [`net.Server.listen()`]: net.html#net_server_listen_handle_callback
1110 [`net.Server.listen(path)`]: net.html#net_server_listen_path_callback
1111 [`net.Server.listen(port)`]: net.html#net_server_listen_port_hostname_backlog_callback
1112 [`net.Socket`]: net.html#net_class_net_socket
1113 [`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
1114 [`response.end()`]: #http_response_end_data_encoding_callback
1115 [`response.write()`]: #http_response_write_chunk_encoding_callback
1116 [`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
1117 [`response.writeContinue()`]: #http_response_writecontinue
1118 [`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
1119 [`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
1120 [`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
1121 [`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
1122 [`stream.setEncoding()`]: stream.html#stream_stream_setencoding_encoding
1123 [`TypeError`]: errors.html#errors_class_typeerror
1124 [`url.parse()`]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
1125 [constructor options]: #http_new_agent_options
1126 [Readable Stream]: stream.html#stream_class_stream_readable
1127 [Writable Stream]: stream.html#stream_class_stream_writable