• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# HTTP
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/http.js -->
8
9To use the HTTP server and client one must `require('http')`.
10
11The HTTP interfaces in Node.js are designed to support many features
12of the protocol which have been traditionally difficult to use.
13In particular, large, possibly chunk-encoded, messages. The interface is
14careful to never buffer entire requests or responses, so the
15user is able to stream data.
16
17HTTP message headers are represented by an object like this:
18
19<!-- eslint-skip -->
20```js
21{ 'content-length': '123',
22  'content-type': 'text/plain',
23  'connection': 'keep-alive',
24  'host': 'mysite.com',
25  'accept': '*/*' }
26```
27
28Keys are lowercased. Values are not modified.
29
30In order to support the full spectrum of possible HTTP applications, the Node.js
31HTTP API is very low-level. It deals with stream handling and message
32parsing only. It parses a message into headers and body but it does not
33parse the actual headers or the body.
34
35See [`message.headers`][] for details on how duplicate headers are handled.
36
37The raw headers as they were received are retained in the `rawHeaders`
38property, which is an array of `[key, value, key2, value2, ...]`. For
39example, the previous message header object might have a `rawHeaders`
40list like the following:
41
42<!-- eslint-disable semi -->
43```js
44[ 'ConTent-Length', '123456',
45  'content-LENGTH', '123',
46  'content-type', 'text/plain',
47  'CONNECTION', 'keep-alive',
48  'Host', 'mysite.com',
49  'accepT', '*/*' ]
50```
51
52## Class: `http.Agent`
53<!-- YAML
54added: v0.3.4
55-->
56
57An `Agent` is responsible for managing connection persistence
58and reuse for HTTP clients. It maintains a queue of pending requests
59for a given host and port, reusing a single socket connection for each
60until the queue is empty, at which time the socket is either destroyed
61or put into a pool where it is kept to be used again for requests to the
62same host and port. Whether it is destroyed or pooled depends on the
63`keepAlive` [option](#http_new_agent_options).
64
65Pooled connections have TCP Keep-Alive enabled for them, but servers may
66still close idle connections, in which case they will be removed from the
67pool and a new connection will be made when a new HTTP request is made for
68that host and port. Servers may also refuse to allow multiple requests
69over the same connection, in which case the connection will have to be
70remade for every request and cannot be pooled. The `Agent` will still make
71the requests to that server, but each one will occur over a new connection.
72
73When a connection is closed by the client or the server, it is removed
74from the pool. Any unused sockets in the pool will be unrefed so as not
75to keep the Node.js process running when there are no outstanding requests.
76(see [`socket.unref()`][]).
77
78It is good practice, to [`destroy()`][] an `Agent` instance when it is no
79longer in use, because unused sockets consume OS resources.
80
81Sockets are removed from an agent when the socket emits either
82a `'close'` event or an `'agentRemove'` event. When intending to keep one
83HTTP request open for a long time without keeping it in the agent, something
84like the following may be done:
85
86```js
87http.get(options, (res) => {
88  // Do stuff
89}).on('socket', (socket) => {
90  socket.emit('agentRemove');
91});
92```
93
94An agent may also be used for an individual request. By providing
95`{agent: false}` as an option to the `http.get()` or `http.request()`
96functions, a one-time use `Agent` with default options will be used
97for the client connection.
98
99`agent:false`:
100
101```js
102http.get({
103  hostname: 'localhost',
104  port: 80,
105  path: '/',
106  agent: false  // Create a new agent just for this one request
107}, (res) => {
108  // Do stuff with response
109});
110```
111
112### `new Agent([options])`
113<!-- YAML
114added: v0.3.4
115changes:
116  - version: v12.19.0
117    pr-url: https://github.com/nodejs/node/pull/33617
118    description: Add `maxTotalSockets` option to agent constructor.
119  - version: v12.20.0
120    pr-url: https://github.com/nodejs/node/pull/33278
121    description: Add `scheduling` option to specify the free socket
122                 scheduling strategy.
123-->
124
125* `options` {Object} Set of configurable options to set on the agent.
126  Can have the following fields:
127  * `keepAlive` {boolean} Keep sockets around even when there are no
128    outstanding requests, so they can be used for future requests without
129    having to reestablish a TCP connection. Not to be confused with the
130    `keep-alive` value of the `Connection` header. The `Connection: keep-alive`
131    header is always sent when using an agent except when the `Connection`
132    header is explicitly specified or when the `keepAlive` and `maxSockets`
133    options are respectively set to `false` and `Infinity`, in which case
134    `Connection: close` will be used. **Default:** `false`.
135  * `keepAliveMsecs` {number} When using the `keepAlive` option, specifies
136    the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay)
137    for TCP Keep-Alive packets. Ignored when the
138    `keepAlive` option is `false` or `undefined`. **Default:** `1000`.
139  * `maxSockets` {number} Maximum number of sockets to allow per
140    host. Each request will use a new socket until the maximum is reached.
141    **Default:** `Infinity`.
142  * `maxTotalSockets` {number} Maximum number of sockets allowed for
143    all hosts in total. Each request will use a new socket
144    until the maximum is reached.
145    **Default:** `Infinity`.
146  * `maxFreeSockets` {number} Maximum number of sockets to leave open
147    in a free state. Only relevant if `keepAlive` is set to `true`.
148    **Default:** `256`.
149  * `scheduling` {string} Scheduling strategy to apply when picking
150    the next free socket to use. It can be `'fifo'` or `'lifo'`.
151    The main difference between the two scheduling strategies is that `'lifo'`
152    selects the most recently used socket, while `'fifo'` selects
153    the least recently used socket.
154    In case of a low rate of request per second, the `'lifo'` scheduling
155    will lower the risk of picking a socket that might have been closed
156    by the server due to inactivity.
157    In case of a high rate of request per second,
158    the `'fifo'` scheduling will maximize the number of open sockets,
159    while the `'lifo'` scheduling will keep it as low as possible.
160    **Default:** `'fifo'`.
161  * `timeout` {number} Socket timeout in milliseconds.
162    This will set the timeout when the socket is created.
163
164`options` in [`socket.connect()`][] are also supported.
165
166The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
167of these values set to their respective defaults.
168
169To configure any of them, a custom [`http.Agent`][] instance must be created.
170
171```js
172const http = require('http');
173const keepAliveAgent = new http.Agent({ keepAlive: true });
174options.agent = keepAliveAgent;
175http.request(options, onResponseCallback);
176```
177
178### `agent.createConnection(options[, callback])`
179<!-- YAML
180added: v0.11.4
181-->
182
183* `options` {Object} Options containing connection details. Check
184  [`net.createConnection()`][] for the format of the options
185* `callback` {Function} Callback function that receives the created socket
186* Returns: {stream.Duplex}
187
188Produces a socket/stream to be used for HTTP requests.
189
190By default, this function is the same as [`net.createConnection()`][]. However,
191custom agents may override this method in case greater flexibility is desired.
192
193A socket/stream can be supplied in one of two ways: by returning the
194socket/stream from this function, or by passing the socket/stream to `callback`.
195
196This method is guaranteed to return an instance of the {net.Socket} class,
197a subclass of {stream.Duplex}, unless the user specifies a socket
198type other than {net.Socket}.
199
200`callback` has a signature of `(err, stream)`.
201
202### `agent.keepSocketAlive(socket)`
203<!-- YAML
204added: v8.1.0
205-->
206
207* `socket` {stream.Duplex}
208
209Called when `socket` is detached from a request and could be persisted by the
210`Agent`. Default behavior is to:
211
212```js
213socket.setKeepAlive(true, this.keepAliveMsecs);
214socket.unref();
215return true;
216```
217
218This method can be overridden by a particular `Agent` subclass. If this
219method returns a falsy value, the socket will be destroyed instead of persisting
220it for use with the next request.
221
222The `socket` argument can be an instance of {net.Socket}, a subclass of
223{stream.Duplex}.
224
225### `agent.reuseSocket(socket, request)`
226<!-- YAML
227added: v8.1.0
228-->
229
230* `socket` {stream.Duplex}
231* `request` {http.ClientRequest}
232
233Called when `socket` is attached to `request` after being persisted because of
234the keep-alive options. Default behavior is to:
235
236```js
237socket.ref();
238```
239
240This method can be overridden by a particular `Agent` subclass.
241
242The `socket` argument can be an instance of {net.Socket}, a subclass of
243{stream.Duplex}.
244
245### `agent.destroy()`
246<!-- YAML
247added: v0.11.4
248-->
249
250Destroy any sockets that are currently in use by the agent.
251
252It is usually not necessary to do this. However, if using an
253agent with `keepAlive` enabled, then it is best to explicitly shut down
254the agent when it will no longer be used. Otherwise,
255sockets may hang open for quite a long time before the server
256terminates them.
257
258### `agent.freeSockets`
259<!-- YAML
260added: v0.11.4
261-->
262
263* {Object}
264
265An object which contains arrays of sockets currently awaiting use by
266the agent when `keepAlive` is enabled. Do not modify.
267
268Sockets in the `freeSockets` list will be automatically destroyed and
269removed from the array on `'timeout'`.
270
271### `agent.getName(options)`
272<!-- YAML
273added: v0.11.4
274-->
275
276* `options` {Object} A set of options providing information for name generation
277  * `host` {string} A domain name or IP address of the server to issue the
278    request to
279  * `port` {number} Port of remote server
280  * `localAddress` {string} Local interface to bind for network connections
281    when issuing the request
282  * `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.
283* Returns: {string}
284
285Get a unique name for a set of request options, to determine whether a
286connection can be reused. For an HTTP agent, this returns
287`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent,
288the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
289that determine socket reusability.
290
291### `agent.maxFreeSockets`
292<!-- YAML
293added: v0.11.7
294-->
295
296* {number}
297
298By default set to 256. For agents with `keepAlive` enabled, this
299sets the maximum number of sockets that will be left open in the free
300state.
301
302### `agent.maxSockets`
303<!-- YAML
304added: v0.3.6
305-->
306
307* {number}
308
309By default set to `Infinity`. Determines how many concurrent sockets the agent
310can have open per origin. Origin is the returned value of [`agent.getName()`][].
311
312### `agent.maxTotalSockets`
313<!-- YAML
314added: v12.19.0
315-->
316
317* {number}
318
319By default set to `Infinity`. Determines how many concurrent sockets the agent
320can have open. Unlike `maxSockets`, this parameter applies across all origins.
321
322### `agent.requests`
323<!-- YAML
324added: v0.5.9
325-->
326
327* {Object}
328
329An object which contains queues of requests that have not yet been assigned to
330sockets. Do not modify.
331
332### `agent.sockets`
333<!-- YAML
334added: v0.3.6
335-->
336
337* {Object}
338
339An object which contains arrays of sockets currently in use by the
340agent. Do not modify.
341
342## Class: `http.ClientRequest`
343<!-- YAML
344added: v0.1.17
345-->
346
347* Extends: {Stream}
348
349This object is created internally and returned from [`http.request()`][]. It
350represents an _in-progress_ request whose header has already been queued. The
351header is still mutable using the [`setHeader(name, value)`][],
352 [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will
353be sent along with the first data chunk or when calling [`request.end()`][].
354
355To get the response, add a listener for [`'response'`][] to the request object.
356[`'response'`][] will be emitted from the request object when the response
357headers have been received. The [`'response'`][] event is executed with one
358argument which is an instance of [`http.IncomingMessage`][].
359
360During the [`'response'`][] event, one can add listeners to the
361response object; particularly to listen for the `'data'` event.
362
363If no [`'response'`][] handler is added, then the response will be
364entirely discarded. However, if a [`'response'`][] event handler is added,
365then the data from the response object **must** be consumed, either by
366calling `response.read()` whenever there is a `'readable'` event, or
367by adding a `'data'` handler, or by calling the `.resume()` method.
368Until the data is consumed, the `'end'` event will not fire. Also, until
369the data is read it will consume memory that can eventually lead to a
370'process out of memory' error.
371
372Unlike the `request` object, if the response closes prematurely, the
373`response` object does not emit an `'error'` event but instead emits the
374`'aborted'` event.
375
376Node.js does not check whether Content-Length and the length of the
377body which has been transmitted are equal or not.
378
379### Event: `'abort'`
380<!-- YAML
381added: v1.4.1
382-->
383
384Emitted when the request has been aborted by the client. This event is only
385emitted on the first call to `abort()`.
386
387### Event: `'connect'`
388<!-- YAML
389added: v0.7.0
390-->
391
392* `response` {http.IncomingMessage}
393* `socket` {stream.Duplex}
394* `head` {Buffer}
395
396Emitted each time a server responds to a request with a `CONNECT` method. If
397this event is not being listened for, clients receiving a `CONNECT` method will
398have their connections closed.
399
400This event is guaranteed to be passed an instance of the {net.Socket} class,
401a subclass of {stream.Duplex}, unless the user specifies a socket
402type other than {net.Socket}.
403
404A client and server pair demonstrating how to listen for the `'connect'` event:
405
406```js
407const http = require('http');
408const net = require('net');
409const { URL } = require('url');
410
411// Create an HTTP tunneling proxy
412const proxy = http.createServer((req, res) => {
413  res.writeHead(200, { 'Content-Type': 'text/plain' });
414  res.end('okay');
415});
416proxy.on('connect', (req, clientSocket, head) => {
417  // Connect to an origin server
418  const { port, hostname } = new URL(`http://${req.url}`);
419  const serverSocket = net.connect(port || 80, hostname, () => {
420    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
421                    'Proxy-agent: Node.js-Proxy\r\n' +
422                    '\r\n');
423    serverSocket.write(head);
424    serverSocket.pipe(clientSocket);
425    clientSocket.pipe(serverSocket);
426  });
427});
428
429// Now that proxy is running
430proxy.listen(1337, '127.0.0.1', () => {
431
432  // Make a request to a tunneling proxy
433  const options = {
434    port: 1337,
435    host: '127.0.0.1',
436    method: 'CONNECT',
437    path: 'www.google.com:80'
438  };
439
440  const req = http.request(options);
441  req.end();
442
443  req.on('connect', (res, socket, head) => {
444    console.log('got connected!');
445
446    // Make a request over an HTTP tunnel
447    socket.write('GET / HTTP/1.1\r\n' +
448                 'Host: www.google.com:80\r\n' +
449                 'Connection: close\r\n' +
450                 '\r\n');
451    socket.on('data', (chunk) => {
452      console.log(chunk.toString());
453    });
454    socket.on('end', () => {
455      proxy.close();
456    });
457  });
458});
459```
460
461### Event: `'continue'`
462<!-- YAML
463added: v0.3.2
464-->
465
466Emitted when the server sends a '100 Continue' HTTP response, usually because
467the request contained 'Expect: 100-continue'. This is an instruction that
468the client should send the request body.
469
470### Event: `'information'`
471<!-- YAML
472added: v10.0.0
473-->
474
475* `info` {Object}
476  * `httpVersion` {string}
477  * `httpVersionMajor` {integer}
478  * `httpVersionMinor` {integer}
479  * `statusCode` {integer}
480  * `statusMessage` {string}
481  * `headers` {Object}
482  * `rawHeaders` {string[]}
483
484Emitted when the server sends a 1xx intermediate response (excluding 101
485Upgrade). The listeners of this event will receive an object containing the
486HTTP version, status code, status message, key-value headers object,
487and array with the raw header names followed by their respective values.
488
489```js
490const http = require('http');
491
492const options = {
493  host: '127.0.0.1',
494  port: 8080,
495  path: '/length_request'
496};
497
498// Make a request
499const req = http.request(options);
500req.end();
501
502req.on('information', (info) => {
503  console.log(`Got information prior to main response: ${info.statusCode}`);
504});
505```
506
507101 Upgrade statuses do not fire this event due to their break from the
508traditional HTTP request/response chain, such as web sockets, in-place TLS
509upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
510[`'upgrade'`][] event instead.
511
512### Event: `'response'`
513<!-- YAML
514added: v0.1.0
515-->
516
517* `response` {http.IncomingMessage}
518
519Emitted when a response is received to this request. This event is emitted only
520once.
521
522### Event: `'socket'`
523<!-- YAML
524added: v0.5.3
525-->
526
527* `socket` {stream.Duplex}
528
529This event is guaranteed to be passed an instance of the {net.Socket} class,
530a subclass of {stream.Duplex}, unless the user specifies a socket
531type other than {net.Socket}.
532
533### Event: `'timeout'`
534<!-- YAML
535added: v0.7.8
536-->
537
538Emitted when the underlying socket times out from inactivity. This only notifies
539that the socket has been idle. The request must be aborted manually.
540
541See also: [`request.setTimeout()`][].
542
543### Event: `'upgrade'`
544<!-- YAML
545added: v0.1.94
546-->
547
548* `response` {http.IncomingMessage}
549* `socket` {stream.Duplex}
550* `head` {Buffer}
551
552Emitted each time a server responds to a request with an upgrade. If this
553event is not being listened for and the response status code is 101 Switching
554Protocols, clients receiving an upgrade header will have their connections
555closed.
556
557This event is guaranteed to be passed an instance of the {net.Socket} class,
558a subclass of {stream.Duplex}, unless the user specifies a socket
559type other than {net.Socket}.
560
561A client server pair demonstrating how to listen for the `'upgrade'` event.
562
563```js
564const http = require('http');
565
566// Create an HTTP server
567const server = http.createServer((req, res) => {
568  res.writeHead(200, { 'Content-Type': 'text/plain' });
569  res.end('okay');
570});
571server.on('upgrade', (req, socket, head) => {
572  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
573               'Upgrade: WebSocket\r\n' +
574               'Connection: Upgrade\r\n' +
575               '\r\n');
576
577  socket.pipe(socket); // echo back
578});
579
580// Now that server is running
581server.listen(1337, '127.0.0.1', () => {
582
583  // make a request
584  const options = {
585    port: 1337,
586    host: '127.0.0.1',
587    headers: {
588      'Connection': 'Upgrade',
589      'Upgrade': 'websocket'
590    }
591  };
592
593  const req = http.request(options);
594  req.end();
595
596  req.on('upgrade', (res, socket, upgradeHead) => {
597    console.log('got upgraded!');
598    socket.end();
599    process.exit(0);
600  });
601});
602```
603
604### `request.abort()`
605<!-- YAML
606added: v0.3.8
607-->
608
609Marks the request as aborting. Calling this will cause remaining data
610in the response to be dropped and the socket to be destroyed.
611
612### `request.aborted`
613<!-- YAML
614added: v0.11.14
615changes:
616  - version: v11.0.0
617    pr-url: https://github.com/nodejs/node/pull/20230
618    description: The `aborted` property is no longer a timestamp number.
619-->
620
621* {boolean}
622
623The `request.aborted` property will be `true` if the request has
624been aborted.
625
626### `request.connection`
627<!-- YAML
628added: v0.3.0
629-->
630
631* {stream.Duplex}
632
633See [`request.socket`][].
634
635### `request.end([data[, encoding]][, callback])`
636<!-- YAML
637added: v0.1.90
638changes:
639  - version: v10.0.0
640    pr-url: https://github.com/nodejs/node/pull/18780
641    description: This method now returns a reference to `ClientRequest`.
642-->
643
644* `data` {string|Buffer}
645* `encoding` {string}
646* `callback` {Function}
647* Returns: {this}
648
649Finishes sending the request. If any parts of the body are
650unsent, it will flush them to the stream. If the request is
651chunked, this will send the terminating `'0\r\n\r\n'`.
652
653If `data` is specified, it is equivalent to calling
654[`request.write(data, encoding)`][] followed by `request.end(callback)`.
655
656If `callback` is specified, it will be called when the request stream
657is finished.
658
659### `request.finished`
660<!-- YAML
661added: v0.0.1
662deprecated: v12.16.0
663-->
664
665> Stability: 0 - Deprecated. Use [`request.writableEnded`][].
666
667* {boolean}
668
669The `request.finished` property will be `true` if [`request.end()`][]
670has been called. `request.end()` will automatically be called if the
671request was initiated via [`http.get()`][].
672
673### `request.flushHeaders()`
674<!-- YAML
675added: v1.6.0
676-->
677
678Flushes the request headers.
679
680For efficiency reasons, Node.js normally buffers the request headers until
681`request.end()` is called or the first chunk of request data is written. It
682then tries to pack the request headers and data into a single TCP packet.
683
684That's usually desired (it saves a TCP round-trip), but not when the first
685data is not sent until possibly much later. `request.flushHeaders()` bypasses
686the optimization and kickstarts the request.
687
688### `request.getHeader(name)`
689<!-- YAML
690added: v1.6.0
691-->
692
693* `name` {string}
694* Returns: {any}
695
696Reads out a header on the request. The name is case-insensitive.
697The type of the return value depends on the arguments provided to
698[`request.setHeader()`][].
699
700```js
701request.setHeader('content-type', 'text/html');
702request.setHeader('Content-Length', Buffer.byteLength(body));
703request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
704const contentType = request.getHeader('Content-Type');
705// 'contentType' is 'text/html'
706const contentLength = request.getHeader('Content-Length');
707// 'contentLength' is of type number
708const cookie = request.getHeader('Cookie');
709// 'cookie' is of type string[]
710```
711
712### `request.maxHeadersCount`
713
714* {number} **Default:** `2000`
715
716Limits maximum response headers count. If set to 0, no limit will be applied.
717
718### `request.path`
719<!-- YAML
720added: v0.4.0
721-->
722
723* {string} The request path.
724
725### `request.method`
726<!-- YAML
727added: v0.1.97
728-->
729
730* {string} The request method.
731
732### `request.host`
733<!-- YAML
734added: v12.19.0
735-->
736
737* {string} The request host.
738
739### `request.protocol`
740<!-- YAML
741added: v12.19.0
742-->
743
744* {string} The request protocol.
745
746### `request.removeHeader(name)`
747<!-- YAML
748added: v1.6.0
749-->
750
751* `name` {string}
752
753Removes a header that's already defined into headers object.
754
755```js
756request.removeHeader('Content-Type');
757```
758
759### `request.reusedSocket`
760
761<!-- YAML
762added: v12.16.0
763-->
764
765* {boolean} Whether the request is send through a reused socket.
766
767When sending request through a keep-alive enabled agent, the underlying socket
768might be reused. But if server closes connection at unfortunate time, client
769may run into a 'ECONNRESET' error.
770
771```js
772const http = require('http');
773
774// Server has a 5 seconds keep-alive timeout by default
775http
776  .createServer((req, res) => {
777    res.write('hello\n');
778    res.end();
779  })
780  .listen(3000);
781
782setInterval(() => {
783  // Adapting a keep-alive agent
784  http.get('http://localhost:3000', { agent }, (res) => {
785    res.on('data', (data) => {
786      // Do nothing
787    });
788  });
789}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
790```
791
792By marking a request whether it reused socket or not, we can do
793automatic error retry base on it.
794
795```js
796const http = require('http');
797const agent = new http.Agent({ keepAlive: true });
798
799function retriableRequest() {
800  const req = http
801    .get('http://localhost:3000', { agent }, (res) => {
802      // ...
803    })
804    .on('error', (err) => {
805      // Check if retry is needed
806      if (req.reusedSocket && err.code === 'ECONNRESET') {
807        retriableRequest();
808      }
809    });
810}
811
812retriableRequest();
813```
814
815### `request.setHeader(name, value)`
816<!-- YAML
817added: v1.6.0
818-->
819
820* `name` {string}
821* `value` {any}
822
823Sets a single header value for headers object. If this header already exists in
824the to-be-sent headers, its value will be replaced. Use an array of strings
825here to send multiple headers with the same name. Non-string values will be
826stored without modification. Therefore, [`request.getHeader()`][] may return
827non-string values. However, the non-string values will be converted to strings
828for network transmission.
829
830```js
831request.setHeader('Content-Type', 'application/json');
832```
833
834or
835
836```js
837request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
838```
839
840### `request.setNoDelay([noDelay])`
841<!-- YAML
842added: v0.5.9
843-->
844
845* `noDelay` {boolean}
846
847Once a socket is assigned to this request and is connected
848[`socket.setNoDelay()`][] will be called.
849
850### `request.setSocketKeepAlive([enable][, initialDelay])`
851<!-- YAML
852added: v0.5.9
853-->
854
855* `enable` {boolean}
856* `initialDelay` {number}
857
858Once a socket is assigned to this request and is connected
859[`socket.setKeepAlive()`][] will be called.
860
861### `request.setTimeout(timeout[, callback])`
862<!-- YAML
863added: v0.5.9
864changes:
865  - version: v9.0.0
866    pr-url: https://github.com/nodejs/node/pull/8895
867    description: Consistently set socket timeout only when the socket connects.
868-->
869
870* `timeout` {number} Milliseconds before a request times out.
871* `callback` {Function} Optional function to be called when a timeout occurs.
872  Same as binding to the `'timeout'` event.
873* Returns: {http.ClientRequest}
874
875Once a socket is assigned to this request and is connected
876[`socket.setTimeout()`][] will be called.
877
878### `request.socket`
879<!-- YAML
880added: v0.3.0
881-->
882
883* {stream.Duplex}
884
885Reference to the underlying socket. Usually users will not want to access
886this property. In particular, the socket will not emit `'readable'` events
887because of how the protocol parser attaches to the socket. The `socket`
888may also be accessed via `request.connection`.
889
890```js
891const http = require('http');
892const options = {
893  host: 'www.google.com',
894};
895const req = http.get(options);
896req.end();
897req.once('response', (res) => {
898  const ip = req.socket.localAddress;
899  const port = req.socket.localPort;
900  console.log(`Your IP address is ${ip} and your source port is ${port}.`);
901  // Consume response object
902});
903```
904
905This property is guaranteed to be an instance of the {net.Socket} class,
906a subclass of {stream.Duplex}, unless the user specified a socket
907type other than {net.Socket}.
908
909### `request.writableEnded`
910<!-- YAML
911added: v12.9.0
912-->
913
914* {boolean}
915
916Is `true` after [`request.end()`][] has been called. This property
917does not indicate whether the data has been flushed, for this use
918[`request.writableFinished`][] instead.
919
920### `request.writableFinished`
921<!-- YAML
922added: v12.7.0
923-->
924
925* {boolean}
926
927Is `true` if all data has been flushed to the underlying system, immediately
928before the [`'finish'`][] event is emitted.
929
930### `request.write(chunk[, encoding][, callback])`
931<!-- YAML
932added: v0.1.29
933-->
934
935* `chunk` {string|Buffer}
936* `encoding` {string}
937* `callback` {Function}
938* Returns: {boolean}
939
940Sends a chunk of the body. By calling this method
941many times, a request body can be sent to a
942server. In that case, it is suggested to use the
943`['Transfer-Encoding', 'chunked']` header line when
944creating the request.
945
946The `encoding` argument is optional and only applies when `chunk` is a string.
947Defaults to `'utf8'`.
948
949The `callback` argument is optional and will be called when this chunk of data
950is flushed, but only if the chunk is non-empty.
951
952Returns `true` if the entire data was flushed successfully to the kernel
953buffer. Returns `false` if all or part of the data was queued in user memory.
954`'drain'` will be emitted when the buffer is free again.
955
956When `write` function is called with empty string or buffer, it does
957nothing and waits for more input.
958
959## Class: `http.Server`
960<!-- YAML
961added: v0.1.17
962-->
963
964* Extends: {net.Server}
965
966### Event: `'checkContinue'`
967<!-- YAML
968added: v0.3.0
969-->
970
971* `request` {http.IncomingMessage}
972* `response` {http.ServerResponse}
973
974Emitted each time a request with an HTTP `Expect: 100-continue` is received.
975If this event is not listened for, the server will automatically respond
976with a `100 Continue` as appropriate.
977
978Handling this event involves calling [`response.writeContinue()`][] if the
979client should continue to send the request body, or generating an appropriate
980HTTP response (e.g. 400 Bad Request) if the client should not continue to send
981the request body.
982
983When this event is emitted and handled, the [`'request'`][] event will
984not be emitted.
985
986### Event: `'checkExpectation'`
987<!-- YAML
988added: v5.5.0
989-->
990
991* `request` {http.IncomingMessage}
992* `response` {http.ServerResponse}
993
994Emitted each time a request with an HTTP `Expect` header is received, where the
995value is not `100-continue`. If this event is not listened for, the server will
996automatically respond with a `417 Expectation Failed` as appropriate.
997
998When this event is emitted and handled, the [`'request'`][] event will
999not be emitted.
1000
1001### Event: `'clientError'`
1002<!-- YAML
1003added: v0.1.94
1004changes:
1005  - version: v6.0.0
1006    pr-url: https://github.com/nodejs/node/pull/4557
1007    description: The default action of calling `.destroy()` on the `socket`
1008                 will no longer take place if there are listeners attached
1009                 for `'clientError'`.
1010  - version: v9.4.0
1011    pr-url: https://github.com/nodejs/node/pull/17672
1012    description: The `rawPacket` is the current buffer that just parsed. Adding
1013                 this buffer to the error object of `'clientError'` event is to
1014                 make it possible that developers can log the broken packet.
1015  - version: v12.0.0
1016    pr-url: https://github.com/nodejs/node/pull/25605
1017    description: The default behavior will return a 431 Request Header
1018                 Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.
1019-->
1020
1021* `exception` {Error}
1022* `socket` {stream.Duplex}
1023
1024If a client connection emits an `'error'` event, it will be forwarded here.
1025Listener of this event is responsible for closing/destroying the underlying
1026socket. For example, one may wish to more gracefully close the socket with a
1027custom HTTP response instead of abruptly severing the connection.
1028
1029This event is guaranteed to be passed an instance of the {net.Socket} class,
1030a subclass of {stream.Duplex}, unless the user specifies a socket
1031type other than {net.Socket}.
1032
1033Default behavior is to try close the socket with a HTTP '400 Bad Request',
1034or a HTTP '431 Request Header Fields Too Large' in the case of a
1035[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable or has already
1036written data it is immediately destroyed.
1037
1038`socket` is the [`net.Socket`][] object that the error originated from.
1039
1040```js
1041const http = require('http');
1042
1043const server = http.createServer((req, res) => {
1044  res.end();
1045});
1046server.on('clientError', (err, socket) => {
1047  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1048});
1049server.listen(8000);
1050```
1051
1052When the `'clientError'` event occurs, there is no `request` or `response`
1053object, so any HTTP response sent, including response headers and payload,
1054*must* be written directly to the `socket` object. Care must be taken to
1055ensure the response is a properly formatted HTTP response message.
1056
1057`err` is an instance of `Error` with two extra columns:
1058
1059* `bytesParsed`: the bytes count of request packet that Node.js may have parsed
1060  correctly;
1061* `rawPacket`: the raw packet of current request.
1062
1063In some cases, the client has already received the response and/or the socket
1064has already been destroyed, like in case of `ECONNRESET` errors. Before
1065trying to send data to the socket, it is better to check that it is still
1066writable.
1067
1068```js
1069server.on('clientError', (err, socket) => {
1070  if (err.code === 'ECONNRESET' || !socket.writable) {
1071    return;
1072  }
1073
1074  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1075});
1076```
1077
1078### Event: `'close'`
1079<!-- YAML
1080added: v0.1.4
1081-->
1082
1083Emitted when the server closes.
1084
1085### Event: `'connect'`
1086<!-- YAML
1087added: v0.7.0
1088-->
1089
1090* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
1091  the [`'request'`][] event
1092* `socket` {stream.Duplex} Network socket between the server and client
1093* `head` {Buffer} The first packet of the tunneling stream (may be empty)
1094
1095Emitted each time a client requests an HTTP `CONNECT` method. If this event is
1096not listened for, then clients requesting a `CONNECT` method will have their
1097connections closed.
1098
1099This event is guaranteed to be passed an instance of the {net.Socket} class,
1100a subclass of {stream.Duplex}, unless the user specifies a socket
1101type other than {net.Socket}.
1102
1103After this event is emitted, the request's socket will not have a `'data'`
1104event listener, meaning it will need to be bound in order to handle data
1105sent to the server on that socket.
1106
1107### Event: `'connection'`
1108<!-- YAML
1109added: v0.1.0
1110-->
1111
1112* `socket` {stream.Duplex}
1113
1114This event is emitted when a new TCP stream is established. `socket` is
1115typically an object of type [`net.Socket`][]. Usually users will not want to
1116access this event. In particular, the socket will not emit `'readable'` events
1117because of how the protocol parser attaches to the socket. The `socket` can
1118also be accessed at `request.connection`.
1119
1120This event can also be explicitly emitted by users to inject connections
1121into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
1122
1123If `socket.setTimeout()` is called here, the timeout will be replaced with
1124`server.keepAliveTimeout` when the socket has served a request (if
1125`server.keepAliveTimeout` is non-zero).
1126
1127This event is guaranteed to be passed an instance of the {net.Socket} class,
1128a subclass of {stream.Duplex}, unless the user specifies a socket
1129type other than {net.Socket}.
1130
1131### Event: `'request'`
1132<!-- YAML
1133added: v0.1.0
1134-->
1135
1136* `request` {http.IncomingMessage}
1137* `response` {http.ServerResponse}
1138
1139Emitted each time there is a request. There may be multiple requests
1140per connection (in the case of HTTP Keep-Alive connections).
1141
1142### Event: `'upgrade'`
1143<!-- YAML
1144added: v0.1.94
1145changes:
1146  - version: v10.0.0
1147    pr-url: v10.0.0
1148    description: Not listening to this event no longer causes the socket
1149                 to be destroyed if a client sends an Upgrade header.
1150-->
1151
1152* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
1153  the [`'request'`][] event
1154* `socket` {stream.Duplex} Network socket between the server and client
1155* `head` {Buffer} The first packet of the upgraded stream (may be empty)
1156
1157Emitted each time a client requests an HTTP upgrade. Listening to this event
1158is optional and clients cannot insist on a protocol change.
1159
1160After this event is emitted, the request's socket will not have a `'data'`
1161event listener, meaning it will need to be bound in order to handle data
1162sent to the server on that socket.
1163
1164This event is guaranteed to be passed an instance of the {net.Socket} class,
1165a subclass of {stream.Duplex}, unless the user specifies a socket
1166type other than {net.Socket}.
1167
1168### `server.close([callback])`
1169<!-- YAML
1170added: v0.1.90
1171-->
1172
1173* `callback` {Function}
1174
1175Stops the server from accepting new connections. See [`net.Server.close()`][].
1176
1177### `server.headersTimeout`
1178<!-- YAML
1179added: v11.3.0
1180-->
1181
1182* {number} **Default:** `60000`
1183
1184Limit the amount of time the parser will wait to receive the complete HTTP
1185headers.
1186
1187In case of inactivity, the rules defined in [`server.timeout`][] apply. However,
1188that inactivity based timeout would still allow the connection to be kept open
1189if the headers are being sent very slowly (by default, up to a byte per 2
1190minutes). In order to prevent this, whenever header data arrives an additional
1191check is made that more than `server.headersTimeout` milliseconds has not
1192passed since the connection was established. If the check fails, a `'timeout'`
1193event is emitted on the server object, and (by default) the socket is destroyed.
1194See [`server.timeout`][] for more information on how timeout behavior can be
1195customized.
1196
1197A value of `0` will disable the HTTP headers timeout check.
1198
1199### `server.listen()`
1200
1201Starts the HTTP server listening for connections.
1202This method is identical to [`server.listen()`][] from [`net.Server`][].
1203
1204### `server.listening`
1205<!-- YAML
1206added: v5.7.0
1207-->
1208
1209* {boolean} Indicates whether or not the server is listening for connections.
1210
1211### `server.maxHeadersCount`
1212<!-- YAML
1213added: v0.7.0
1214-->
1215
1216* {number} **Default:** `2000`
1217
1218Limits maximum incoming headers count. If set to 0, no limit will be applied.
1219
1220### `server.setTimeout([msecs][, callback])`
1221<!-- YAML
1222added: v0.9.12
1223-->
1224
1225* `msecs` {number} **Default:** `120000` (2 minutes)
1226* `callback` {Function}
1227* Returns: {http.Server}
1228
1229Sets the timeout value for sockets, and emits a `'timeout'` event on
1230the Server object, passing the socket as an argument, if a timeout
1231occurs.
1232
1233If there is a `'timeout'` event listener on the Server object, then it
1234will be called with the timed-out socket as an argument.
1235
1236By default, the Server's timeout value is 2 minutes, and sockets are
1237destroyed automatically if they time out. However, if a callback is assigned
1238to the Server's `'timeout'` event, timeouts must be handled explicitly.
1239
1240To change the default timeout use the [`--http-server-default-timeout`][]
1241flag.
1242
1243### `server.timeout`
1244<!-- YAML
1245added: v0.9.12
1246-->
1247
1248* {number} Timeout in milliseconds. **Default:** `120000` (2 minutes).
1249
1250The number of milliseconds of inactivity before a socket is presumed
1251to have timed out.
1252
1253A value of `0` will disable the timeout behavior on incoming connections.
1254
1255The socket timeout logic is set up on connection, so changing this
1256value only affects new connections to the server, not any existing connections.
1257
1258To change the default timeout use the [`--http-server-default-timeout`][]
1259flag.
1260
1261### `server.keepAliveTimeout`
1262<!-- YAML
1263added: v8.0.0
1264-->
1265
1266* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).
1267
1268The number of milliseconds of inactivity a server needs to wait for additional
1269incoming data, after it has finished writing the last response, before a socket
1270will be destroyed. If the server receives new data before the keep-alive
1271timeout has fired, it will reset the regular inactivity timeout, i.e.,
1272[`server.timeout`][].
1273
1274A value of `0` will disable the keep-alive timeout behavior on incoming
1275connections.
1276A value of `0` makes the http server behave similarly to Node.js versions prior
1277to 8.0.0, which did not have a keep-alive timeout.
1278
1279The socket timeout logic is set up on connection, so changing this value only
1280affects new connections to the server, not any existing connections.
1281
1282## Class: `http.ServerResponse`
1283<!-- YAML
1284added: v0.1.17
1285-->
1286
1287* Extends: {Stream}
1288
1289This object is created internally by an HTTP server, not by the user. It is
1290passed as the second parameter to the [`'request'`][] event.
1291
1292### Event: `'close'`
1293<!-- YAML
1294added: v0.6.7
1295-->
1296
1297Indicates that the the response is completed, or its underlying connection was
1298terminated prematurely (before the response completion).
1299
1300### Event: `'finish'`
1301<!-- YAML
1302added: v0.3.6
1303-->
1304
1305Emitted when the response has been sent. More specifically, this event is
1306emitted when the last segment of the response headers and body have been
1307handed off to the operating system for transmission over the network. It
1308does not imply that the client has received anything yet.
1309
1310### `response.addTrailers(headers)`
1311<!-- YAML
1312added: v0.3.0
1313-->
1314
1315* `headers` {Object}
1316
1317This method adds HTTP trailing headers (a header but at the end of the
1318message) to the response.
1319
1320Trailers will **only** be emitted if chunked encoding is used for the
1321response; if it is not (e.g. if the request was HTTP/1.0), they will
1322be silently discarded.
1323
1324HTTP requires the `Trailer` header to be sent in order to
1325emit trailers, with a list of the header fields in its value. E.g.,
1326
1327```js
1328response.writeHead(200, { 'Content-Type': 'text/plain',
1329                          'Trailer': 'Content-MD5' });
1330response.write(fileData);
1331response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
1332response.end();
1333```
1334
1335Attempting to set a header field name or value that contains invalid characters
1336will result in a [`TypeError`][] being thrown.
1337
1338### `response.connection`
1339<!-- YAML
1340added: v0.3.0
1341-->
1342
1343* {stream.Duplex}
1344
1345See [`response.socket`][].
1346
1347### `response.cork()`
1348<!-- YAML
1349added: v12.16.0
1350-->
1351
1352See [`writable.cork()`][].
1353
1354### `response.end([data[, encoding]][, callback])`
1355<!-- YAML
1356added: v0.1.90
1357changes:
1358  - version: v10.0.0
1359    pr-url: https://github.com/nodejs/node/pull/18780
1360    description: This method now returns a reference to `ServerResponse`.
1361-->
1362
1363* `data` {string|Buffer}
1364* `encoding` {string}
1365* `callback` {Function}
1366* Returns: {this}
1367
1368This method signals to the server that all of the response headers and body
1369have been sent; that server should consider this message complete.
1370The method, `response.end()`, MUST be called on each response.
1371
1372If `data` is specified, it is similar in effect to calling
1373[`response.write(data, encoding)`][] followed by `response.end(callback)`.
1374
1375If `callback` is specified, it will be called when the response stream
1376is finished.
1377
1378### `response.finished`
1379<!-- YAML
1380added: v0.0.2
1381deprecated: v12.16.0
1382-->
1383
1384> Stability: 0 - Deprecated. Use [`response.writableEnded`][].
1385
1386* {boolean}
1387
1388The `response.finished` property will be `true` if [`response.end()`][]
1389has been called.
1390
1391### `response.flushHeaders()`
1392<!-- YAML
1393added: v1.6.0
1394-->
1395
1396Flushes the response headers. See also: [`request.flushHeaders()`][].
1397
1398### `response.getHeader(name)`
1399<!-- YAML
1400added: v0.4.0
1401-->
1402
1403* `name` {string}
1404* Returns: {any}
1405
1406Reads out a header that's already been queued but not sent to the client.
1407The name is case-insensitive. The type of the return value depends
1408on the arguments provided to [`response.setHeader()`][].
1409
1410```js
1411response.setHeader('Content-Type', 'text/html');
1412response.setHeader('Content-Length', Buffer.byteLength(body));
1413response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
1414const contentType = response.getHeader('content-type');
1415// contentType is 'text/html'
1416const contentLength = response.getHeader('Content-Length');
1417// contentLength is of type number
1418const setCookie = response.getHeader('set-cookie');
1419// setCookie is of type string[]
1420```
1421
1422### `response.getHeaderNames()`
1423<!-- YAML
1424added: v7.7.0
1425-->
1426
1427* Returns: {string[]}
1428
1429Returns an array containing the unique names of the current outgoing headers.
1430All header names are lowercase.
1431
1432```js
1433response.setHeader('Foo', 'bar');
1434response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
1435
1436const headerNames = response.getHeaderNames();
1437// headerNames === ['foo', 'set-cookie']
1438```
1439
1440### `response.getHeaders()`
1441<!-- YAML
1442added: v7.7.0
1443-->
1444
1445* Returns: {Object}
1446
1447Returns a shallow copy of the current outgoing headers. Since a shallow copy
1448is used, array values may be mutated without additional calls to various
1449header-related http module methods. The keys of the returned object are the
1450header names and the values are the respective header values. All header names
1451are lowercase.
1452
1453The object returned by the `response.getHeaders()` method _does not_
1454prototypically inherit from the JavaScript `Object`. This means that typical
1455`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others
1456are not defined and *will not work*.
1457
1458```js
1459response.setHeader('Foo', 'bar');
1460response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
1461
1462const headers = response.getHeaders();
1463// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
1464```
1465
1466### `response.hasHeader(name)`
1467<!-- YAML
1468added: v7.7.0
1469-->
1470
1471* `name` {string}
1472* Returns: {boolean}
1473
1474Returns `true` if the header identified by `name` is currently set in the
1475outgoing headers. The header name matching is case-insensitive.
1476
1477```js
1478const hasContentType = response.hasHeader('content-type');
1479```
1480
1481### `response.headersSent`
1482<!-- YAML
1483added: v0.9.3
1484-->
1485
1486* {boolean}
1487
1488Boolean (read-only). True if headers were sent, false otherwise.
1489
1490### `response.removeHeader(name)`
1491<!-- YAML
1492added: v0.4.0
1493-->
1494
1495* `name` {string}
1496
1497Removes a header that's queued for implicit sending.
1498
1499```js
1500response.removeHeader('Content-Encoding');
1501```
1502
1503### `response.sendDate`
1504<!-- YAML
1505added: v0.7.5
1506-->
1507
1508* {boolean}
1509
1510When true, the Date header will be automatically generated and sent in
1511the response if it is not already present in the headers. Defaults to true.
1512
1513This should only be disabled for testing; HTTP requires the Date header
1514in responses.
1515
1516### `response.setHeader(name, value)`
1517<!-- YAML
1518added: v0.4.0
1519-->
1520
1521* `name` {string}
1522* `value` {any}
1523
1524Sets a single header value for implicit headers. If this header already exists
1525in the to-be-sent headers, its value will be replaced. Use an array of strings
1526here to send multiple headers with the same name. Non-string values will be
1527stored without modification. Therefore, [`response.getHeader()`][] may return
1528non-string values. However, the non-string values will be converted to strings
1529for network transmission.
1530
1531```js
1532response.setHeader('Content-Type', 'text/html');
1533```
1534
1535or
1536
1537```js
1538response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
1539```
1540
1541Attempting to set a header field name or value that contains invalid characters
1542will result in a [`TypeError`][] being thrown.
1543
1544When headers have been set with [`response.setHeader()`][], they will be merged
1545with any headers passed to [`response.writeHead()`][], with the headers passed
1546to [`response.writeHead()`][] given precedence.
1547
1548```js
1549// Returns content-type = text/plain
1550const server = http.createServer((req, res) => {
1551  res.setHeader('Content-Type', 'text/html');
1552  res.setHeader('X-Foo', 'bar');
1553  res.writeHead(200, { 'Content-Type': 'text/plain' });
1554  res.end('ok');
1555});
1556```
1557
1558If [`response.writeHead()`][] method is called and this method has not been
1559called, it will directly write the supplied header values onto the network
1560channel without caching internally, and the [`response.getHeader()`][] on the
1561header will not yield the expected result. If progressive population of headers
1562is desired with potential future retrieval and modification, use
1563[`response.setHeader()`][] instead of [`response.writeHead()`][].
1564
1565### `response.setTimeout(msecs[, callback])`
1566<!-- YAML
1567added: v0.9.12
1568-->
1569
1570* `msecs` {number}
1571* `callback` {Function}
1572* Returns: {http.ServerResponse}
1573
1574Sets the Socket's timeout value to `msecs`. If a callback is
1575provided, then it is added as a listener on the `'timeout'` event on
1576the response object.
1577
1578If no `'timeout'` listener is added to the request, the response, or
1579the server, then sockets are destroyed when they time out. If a handler is
1580assigned to the request, the response, or the server's `'timeout'` events,
1581timed out sockets must be handled explicitly.
1582
1583### `response.socket`
1584<!-- YAML
1585added: v0.3.0
1586-->
1587
1588* {stream.Duplex}
1589
1590Reference to the underlying socket. Usually users will not want to access
1591this property. In particular, the socket will not emit `'readable'` events
1592because of how the protocol parser attaches to the socket. After
1593`response.end()`, the property is nulled. The `socket` may also be accessed
1594via `response.connection`.
1595
1596```js
1597const http = require('http');
1598const server = http.createServer((req, res) => {
1599  const ip = res.socket.remoteAddress;
1600  const port = res.socket.remotePort;
1601  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
1602}).listen(3000);
1603```
1604
1605This property is guaranteed to be an instance of the {net.Socket} class,
1606a subclass of {stream.Duplex}, unless the user specified a socket
1607type other than {net.Socket}.
1608
1609### `response.statusCode`
1610<!-- YAML
1611added: v0.4.0
1612-->
1613
1614* {number} **Default:** `200`
1615
1616When using implicit headers (not calling [`response.writeHead()`][] explicitly),
1617this property controls the status code that will be sent to the client when
1618the headers get flushed.
1619
1620```js
1621response.statusCode = 404;
1622```
1623
1624After response header was sent to the client, this property indicates the
1625status code which was sent out.
1626
1627### `response.statusMessage`
1628<!-- YAML
1629added: v0.11.8
1630-->
1631
1632* {string}
1633
1634When using implicit headers (not calling [`response.writeHead()`][] explicitly),
1635this property controls the status message that will be sent to the client when
1636the headers get flushed. If this is left as `undefined` then the standard
1637message for the status code will be used.
1638
1639```js
1640response.statusMessage = 'Not found';
1641```
1642
1643After response header was sent to the client, this property indicates the
1644status message which was sent out.
1645
1646### `response.uncork()`
1647<!-- YAML
1648added: v12.16.0
1649-->
1650
1651See [`writable.uncork()`][].
1652
1653### `response.writableEnded`
1654<!-- YAML
1655added: v12.9.0
1656-->
1657
1658* {boolean}
1659
1660Is `true` after [`response.end()`][] has been called. This property
1661does not indicate whether the data has been flushed, for this use
1662[`response.writableFinished`][] instead.
1663
1664### `response.writableFinished`
1665<!-- YAML
1666added: v12.7.0
1667-->
1668
1669* {boolean}
1670
1671Is `true` if all data has been flushed to the underlying system, immediately
1672before the [`'finish'`][] event is emitted.
1673
1674### `response.write(chunk[, encoding][, callback])`
1675<!-- YAML
1676added: v0.1.29
1677-->
1678
1679* `chunk` {string|Buffer}
1680* `encoding` {string} **Default:** `'utf8'`
1681* `callback` {Function}
1682* Returns: {boolean}
1683
1684If this method is called and [`response.writeHead()`][] has not been called,
1685it will switch to implicit header mode and flush the implicit headers.
1686
1687This sends a chunk of the response body. This method may
1688be called multiple times to provide successive parts of the body.
1689
1690In the `http` module, the response body is omitted when the
1691request is a HEAD request. Similarly, the `204` and `304` responses
1692_must not_ include a message body.
1693
1694`chunk` can be a string or a buffer. If `chunk` is a string,
1695the second parameter specifies how to encode it into a byte stream.
1696`callback` will be called when this chunk of data is flushed.
1697
1698This is the raw HTTP body and has nothing to do with higher-level multi-part
1699body encodings that may be used.
1700
1701The first time [`response.write()`][] is called, it will send the buffered
1702header information and the first chunk of the body to the client. The second
1703time [`response.write()`][] is called, Node.js assumes data will be streamed,
1704and sends the new data separately. That is, the response is buffered up to the
1705first chunk of the body.
1706
1707Returns `true` if the entire data was flushed successfully to the kernel
1708buffer. Returns `false` if all or part of the data was queued in user memory.
1709`'drain'` will be emitted when the buffer is free again.
1710
1711### `response.writeContinue()`
1712<!-- YAML
1713added: v0.3.0
1714-->
1715
1716Sends a HTTP/1.1 100 Continue message to the client, indicating that
1717the request body should be sent. See the [`'checkContinue'`][] event on
1718`Server`.
1719
1720### `response.writeHead(statusCode[, statusMessage][, headers])`
1721<!-- YAML
1722added: v0.1.30
1723changes:
1724  - version: v11.10.0
1725    pr-url: https://github.com/nodejs/node/pull/25974
1726    description: Return `this` from `writeHead()` to allow chaining with
1727                 `end()`.
1728  - version: v5.11.0, v4.4.5
1729    pr-url: https://github.com/nodejs/node/pull/6291
1730    description: A `RangeError` is thrown if `statusCode` is not a number in
1731                 the range `[100, 999]`.
1732-->
1733
1734* `statusCode` {number}
1735* `statusMessage` {string}
1736* `headers` {Object}
1737* Returns: {http.ServerResponse}
1738
1739Sends a response header to the request. The status code is a 3-digit HTTP
1740status code, like `404`. The last argument, `headers`, are the response headers.
1741Optionally one can give a human-readable `statusMessage` as the second
1742argument.
1743
1744Returns a reference to the `ServerResponse`, so that calls can be chained.
1745
1746```js
1747const body = 'hello world';
1748response
1749  .writeHead(200, {
1750    'Content-Length': Buffer.byteLength(body),
1751    'Content-Type': 'text/plain'
1752  })
1753  .end(body);
1754```
1755
1756This method must only be called once on a message and it must
1757be called before [`response.end()`][] is called.
1758
1759If [`response.write()`][] or [`response.end()`][] are called before calling
1760this, the implicit/mutable headers will be calculated and call this function.
1761
1762When headers have been set with [`response.setHeader()`][], they will be merged
1763with any headers passed to [`response.writeHead()`][], with the headers passed
1764to [`response.writeHead()`][] given precedence.
1765
1766If this method is called and [`response.setHeader()`][] has not been called,
1767it will directly write the supplied header values onto the network channel
1768without caching internally, and the [`response.getHeader()`][] on the header
1769will not yield the expected result. If progressive population of headers is
1770desired with potential future retrieval and modification, use
1771[`response.setHeader()`][] instead.
1772
1773```js
1774// Returns content-type = text/plain
1775const server = http.createServer((req, res) => {
1776  res.setHeader('Content-Type', 'text/html');
1777  res.setHeader('X-Foo', 'bar');
1778  res.writeHead(200, { 'Content-Type': 'text/plain' });
1779  res.end('ok');
1780});
1781```
1782
1783`Content-Length` is given in bytes, not characters. Use
1784[`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js
1785does not check whether `Content-Length` and the length of the body which has
1786been transmitted are equal or not.
1787
1788Attempting to set a header field name or value that contains invalid characters
1789will result in a [`TypeError`][] being thrown.
1790
1791### `response.writeProcessing()`
1792<!-- YAML
1793added: v10.0.0
1794-->
1795
1796Sends a HTTP/1.1 102 Processing message to the client, indicating that
1797the request body should be sent.
1798
1799## Class: `http.IncomingMessage`
1800<!-- YAML
1801added: v0.1.17
1802changes:
1803  - version: v12.16.0
1804    pr-url: https://github.com/nodejs/node/pull/30135
1805    description: The `readableHighWaterMark` value mirrors that of the socket.
1806-->
1807
1808* Extends: {stream.Readable}
1809
1810An `IncomingMessage` object is created by [`http.Server`][] or
1811[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][]
1812and [`'response'`][] event respectively. It may be used to access response
1813status, headers and data.
1814
1815### Event: `'aborted'`
1816<!-- YAML
1817added: v0.3.8
1818-->
1819
1820Emitted when the request has been aborted.
1821
1822### Event: `'close'`
1823<!-- YAML
1824added: v0.4.2
1825-->
1826
1827Indicates that the underlying connection was closed.
1828
1829### `message.aborted`
1830<!-- YAML
1831added: v10.1.0
1832-->
1833
1834* {boolean}
1835
1836The `message.aborted` property will be `true` if the request has
1837been aborted.
1838
1839### `message.complete`
1840<!-- YAML
1841added: v0.3.0
1842-->
1843
1844* {boolean}
1845
1846The `message.complete` property will be `true` if a complete HTTP message has
1847been received and successfully parsed.
1848
1849This property is particularly useful as a means of determining if a client or
1850server fully transmitted a message before a connection was terminated:
1851
1852```js
1853const req = http.request({
1854  host: '127.0.0.1',
1855  port: 8080,
1856  method: 'POST'
1857}, (res) => {
1858  res.resume();
1859  res.on('end', () => {
1860    if (!res.complete)
1861      console.error(
1862        'The connection was terminated while the message was still being sent');
1863  });
1864});
1865```
1866
1867### `message.destroy([error])`
1868<!-- YAML
1869added: v0.3.0
1870changes:
1871  - version: v12.19.0
1872    pr-url: https://github.com/nodejs/node/pull/32789
1873    description: The function returns `this` for consistency with other Readable
1874                 streams.
1875-->
1876
1877* `error` {Error}
1878* Returns: {this}
1879
1880Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`
1881is provided, an `'error'` event is emitted on the socket and `error` is passed
1882as an argument to any listeners on the event.
1883
1884### `message.headers`
1885<!-- YAML
1886added: v0.1.5
1887-->
1888
1889* {Object}
1890
1891The request/response headers object.
1892
1893Key-value pairs of header names and values. Header names are lower-cased.
1894
1895```js
1896// Prints something like:
1897//
1898// { 'user-agent': 'curl/7.22.0',
1899//   host: '127.0.0.1:8000',
1900//   accept: '*/*' }
1901console.log(request.headers);
1902```
1903
1904Duplicates in raw headers are handled in the following ways, depending on the
1905header name:
1906
1907* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
1908`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
1909`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
1910`retry-after`, `server`, or `user-agent` are discarded.
1911* `set-cookie` is always an array. Duplicates are added to the array.
1912* For duplicate `cookie` headers, the values are joined together with '; '.
1913* For all other headers, the values are joined together with ', '.
1914
1915### `message.httpVersion`
1916<!-- YAML
1917added: v0.1.1
1918-->
1919
1920* {string}
1921
1922In case of server request, the HTTP version sent by the client. In the case of
1923client response, the HTTP version of the connected-to server.
1924Probably either `'1.1'` or `'1.0'`.
1925
1926Also `message.httpVersionMajor` is the first integer and
1927`message.httpVersionMinor` is the second.
1928
1929### `message.method`
1930<!-- YAML
1931added: v0.1.1
1932-->
1933
1934* {string}
1935
1936**Only valid for request obtained from [`http.Server`][].**
1937
1938The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
1939
1940### `message.rawHeaders`
1941<!-- YAML
1942added: v0.11.6
1943-->
1944
1945* {string[]}
1946
1947The raw request/response headers list exactly as they were received.
1948
1949The keys and values are in the same list. It is *not* a
1950list of tuples. So, the even-numbered offsets are key values, and the
1951odd-numbered offsets are the associated values.
1952
1953Header names are not lowercased, and duplicates are not merged.
1954
1955```js
1956// Prints something like:
1957//
1958// [ 'user-agent',
1959//   'this is invalid because there can be only one',
1960//   'User-Agent',
1961//   'curl/7.22.0',
1962//   'Host',
1963//   '127.0.0.1:8000',
1964//   'ACCEPT',
1965//   '*/*' ]
1966console.log(request.rawHeaders);
1967```
1968
1969### `message.rawTrailers`
1970<!-- YAML
1971added: v0.11.6
1972-->
1973
1974* {string[]}
1975
1976The raw request/response trailer keys and values exactly as they were
1977received. Only populated at the `'end'` event.
1978
1979### `message.setTimeout(msecs[, callback])`
1980<!-- YAML
1981added: v0.5.9
1982-->
1983
1984* `msecs` {number}
1985* `callback` {Function}
1986* Returns: {http.IncomingMessage}
1987
1988Calls `message.connection.setTimeout(msecs, callback)`.
1989
1990### `message.socket`
1991<!-- YAML
1992added: v0.3.0
1993-->
1994
1995* {stream.Duplex}
1996
1997The [`net.Socket`][] object associated with the connection.
1998
1999With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
2000client's authentication details.
2001
2002This property is guaranteed to be an instance of the {net.Socket} class,
2003a subclass of {stream.Duplex}, unless the user specified a socket
2004type other than {net.Socket}.
2005
2006### `message.statusCode`
2007<!-- YAML
2008added: v0.1.1
2009-->
2010
2011* {number}
2012
2013**Only valid for response obtained from [`http.ClientRequest`][].**
2014
2015The 3-digit HTTP response status code. E.G. `404`.
2016
2017### `message.statusMessage`
2018<!-- YAML
2019added: v0.11.10
2020-->
2021
2022* {string}
2023
2024**Only valid for response obtained from [`http.ClientRequest`][].**
2025
2026The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server
2027Error`.
2028
2029### `message.trailers`
2030<!-- YAML
2031added: v0.3.0
2032-->
2033
2034* {Object}
2035
2036The request/response trailers object. Only populated at the `'end'` event.
2037
2038### `message.url`
2039<!-- YAML
2040added: v0.1.90
2041-->
2042
2043* {string}
2044
2045**Only valid for request obtained from [`http.Server`][].**
2046
2047Request URL string. This contains only the URL that is present in the actual
2048HTTP request. Take the following request:
2049
2050```http
2051GET /status?name=ryan HTTP/1.1
2052Accept: text/plain
2053```
2054
2055To parse the URL into its parts:
2056
2057```js
2058new URL(request.url, `http://${request.headers.host}`);
2059```
2060
2061When `request.url` is `'/status?name=ryan'` and
2062`request.headers.host` is `'localhost:3000'`:
2063
2064```console
2065$ node
2066> new URL(request.url, `http://${request.headers.host}`)
2067URL {
2068  href: 'http://localhost:3000/status?name=ryan',
2069  origin: 'http://localhost:3000',
2070  protocol: 'http:',
2071  username: '',
2072  password: '',
2073  host: 'localhost:3000',
2074  hostname: 'localhost',
2075  port: '3000',
2076  pathname: '/status',
2077  search: '?name=ryan',
2078  searchParams: URLSearchParams { 'name' => 'ryan' },
2079  hash: ''
2080}
2081```
2082
2083## `http.METHODS`
2084<!-- YAML
2085added: v0.11.8
2086-->
2087
2088* {string[]}
2089
2090A list of the HTTP methods that are supported by the parser.
2091
2092## `http.STATUS_CODES`
2093<!-- YAML
2094added: v0.1.22
2095-->
2096
2097* {Object}
2098
2099A collection of all the standard HTTP response status codes, and the
2100short description of each. For example, `http.STATUS_CODES[404] === 'Not
2101Found'`.
2102
2103## `http.createServer([options][, requestListener])`
2104<!-- YAML
2105added: v0.1.13
2106changes:
2107  - version: v12.15.0
2108    pr-url: https://github.com/nodejs/node/pull/31448
2109    description: The `insecureHTTPParser` option is supported now.
2110  - version: v9.6.0, v8.12.0
2111    pr-url: https://github.com/nodejs/node/pull/15752
2112    description: The `options` argument is supported now.
2113-->
2114
2115* `options` {Object}
2116  * `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage`
2117    class to be used. Useful for extending the original `IncomingMessage`.
2118    **Default:** `IncomingMessage`.
2119  * `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class
2120    to be used. Useful for extending the original `ServerResponse`. **Default:**
2121    `ServerResponse`.
2122  * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
2123    invalid HTTP headers when `true`. Using the insecure parser should be
2124    avoided. See [`--insecure-http-parser`][] for more information.
2125    **Default:** `false`
2126* `requestListener` {Function}
2127
2128* Returns: {http.Server}
2129
2130Returns a new instance of [`http.Server`][].
2131
2132The `requestListener` is a function which is automatically
2133added to the [`'request'`][] event.
2134
2135## `http.get(options[, callback])`
2136## `http.get(url[, options][, callback])`
2137<!-- YAML
2138added: v0.3.6
2139changes:
2140  - version: v10.9.0
2141    pr-url: https://github.com/nodejs/node/pull/21616
2142    description: The `url` parameter can now be passed along with a separate
2143                 `options` object.
2144  - version: v7.5.0
2145    pr-url: https://github.com/nodejs/node/pull/10638
2146    description: The `options` parameter can be a WHATWG `URL` object.
2147-->
2148
2149* `url` {string | URL}
2150* `options` {Object} Accepts the same `options` as
2151  [`http.request()`][], with the `method` always set to `GET`.
2152  Properties that are inherited from the prototype are ignored.
2153* `callback` {Function}
2154* Returns: {http.ClientRequest}
2155
2156Since most requests are GET requests without bodies, Node.js provides this
2157convenience method. The only difference between this method and
2158[`http.request()`][] is that it sets the method to GET and calls `req.end()`
2159automatically. The callback must take care to consume the response
2160data for reasons stated in [`http.ClientRequest`][] section.
2161
2162The `callback` is invoked with a single argument that is an instance of
2163[`http.IncomingMessage`][].
2164
2165JSON fetching example:
2166
2167```js
2168http.get('http://nodejs.org/dist/index.json', (res) => {
2169  const { statusCode } = res;
2170  const contentType = res.headers['content-type'];
2171
2172  let error;
2173  // Any 2xx status code signals a successful response but
2174  // here we're only checking for 200.
2175  if (statusCode !== 200) {
2176    error = new Error('Request Failed.\n' +
2177                      `Status Code: ${statusCode}`);
2178  } else if (!/^application\/json/.test(contentType)) {
2179    error = new Error('Invalid content-type.\n' +
2180                      `Expected application/json but received ${contentType}`);
2181  }
2182  if (error) {
2183    console.error(error.message);
2184    // Consume response data to free up memory
2185    res.resume();
2186    return;
2187  }
2188
2189  res.setEncoding('utf8');
2190  let rawData = '';
2191  res.on('data', (chunk) => { rawData += chunk; });
2192  res.on('end', () => {
2193    try {
2194      const parsedData = JSON.parse(rawData);
2195      console.log(parsedData);
2196    } catch (e) {
2197      console.error(e.message);
2198    }
2199  });
2200}).on('error', (e) => {
2201  console.error(`Got error: ${e.message}`);
2202});
2203```
2204
2205## `http.globalAgent`
2206<!-- YAML
2207added: v0.5.9
2208-->
2209
2210* {http.Agent}
2211
2212Global instance of `Agent` which is used as the default for all HTTP client
2213requests.
2214
2215## `http.maxHeaderSize`
2216<!-- YAML
2217added: v11.6.0
2218-->
2219
2220* {number}
2221
2222Read-only property specifying the maximum allowed size of HTTP headers in bytes.
2223Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option.
2224
2225## `http.request(options[, callback])`
2226## `http.request(url[, options][, callback])`
2227<!-- YAML
2228added: v0.3.6
2229changes:
2230  - version: v12.15.0
2231    pr-url: https://github.com/nodejs/node/pull/31448
2232    description: The `insecureHTTPParser` option is supported now.
2233  - version: v10.9.0
2234    pr-url: https://github.com/nodejs/node/pull/21616
2235    description: The `url` parameter can now be passed along with a separate
2236                 `options` object.
2237  - version: v7.5.0
2238    pr-url: https://github.com/nodejs/node/pull/10638
2239    description: The `options` parameter can be a WHATWG `URL` object.
2240-->
2241
2242* `url` {string | URL}
2243* `options` {Object}
2244  * `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible
2245    values:
2246    * `undefined` (default): use [`http.globalAgent`][] for this host and port.
2247    * `Agent` object: explicitly use the passed in `Agent`.
2248    * `false`: causes a new `Agent` with default values to be used.
2249  * `auth` {string} Basic authentication i.e. `'user:password'` to compute an
2250    Authorization header.
2251  * `createConnection` {Function} A function that produces a socket/stream to
2252    use for the request when the `agent` option is not used. This can be used to
2253    avoid creating a custom `Agent` class just to override the default
2254    `createConnection` function. See [`agent.createConnection()`][] for more
2255    details. Any [`Duplex`][] stream is a valid return value.
2256  * `defaultPort` {number} Default port for the protocol. **Default:**
2257    `agent.defaultPort` if an `Agent` is used, else `undefined`.
2258  * `family` {number} IP address family to use when resolving `host` or
2259    `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and
2260    v6 will be used.
2261  * `headers` {Object} An object containing request headers.
2262  * `host` {string} A domain name or IP address of the server to issue the
2263    request to. **Default:** `'localhost'`.
2264  * `hostname` {string} Alias for `host`. To support [`url.parse()`][],
2265    `hostname` will be used if both `host` and `hostname` are specified.
2266  * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
2267    invalid HTTP headers when `true`. Using the insecure parser should be
2268    avoided. See [`--insecure-http-parser`][] for more information.
2269    **Default:** `false`
2270  * `localAddress` {string} Local interface to bind for network connections.
2271  * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
2272  * `method` {string} A string specifying the HTTP request method. **Default:**
2273    `'GET'`.
2274  * `path` {string} Request path. Should include query string if any.
2275    E.G. `'/index.html?page=12'`. An exception is thrown when the request path
2276    contains illegal characters. Currently, only spaces are rejected but that
2277    may change in the future. **Default:** `'/'`.
2278  * `port` {number} Port of remote server. **Default:** `defaultPort` if set,
2279    else `80`.
2280  * `protocol` {string} Protocol to use. **Default:** `'http:'`.
2281  * `setHost` {boolean}: Specifies whether or not to automatically add the
2282    `Host` header. Defaults to `true`.
2283  * `socketPath` {string} Unix Domain Socket (cannot be used if one of `host`
2284     or `port` is specified, those specify a TCP Socket).
2285  * `timeout` {number}: A number specifying the socket timeout in milliseconds.
2286    This will set the timeout before the socket is connected.
2287* `callback` {Function}
2288* Returns: {http.ClientRequest}
2289
2290Node.js maintains several connections per server to make HTTP requests.
2291This function allows one to transparently issue requests.
2292
2293`url` can be a string or a [`URL`][] object. If `url` is a
2294string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][]
2295object, it will be automatically converted to an ordinary `options` object.
2296
2297If both `url` and `options` are specified, the objects are merged, with the
2298`options` properties taking precedence.
2299
2300The optional `callback` parameter will be added as a one-time listener for
2301the [`'response'`][] event.
2302
2303`http.request()` returns an instance of the [`http.ClientRequest`][]
2304class. The `ClientRequest` instance is a writable stream. If one needs to
2305upload a file with a POST request, then write to the `ClientRequest` object.
2306
2307```js
2308const postData = querystring.stringify({
2309  'msg': 'Hello World!'
2310});
2311
2312const options = {
2313  hostname: 'www.google.com',
2314  port: 80,
2315  path: '/upload',
2316  method: 'POST',
2317  headers: {
2318    'Content-Type': 'application/x-www-form-urlencoded',
2319    'Content-Length': Buffer.byteLength(postData)
2320  }
2321};
2322
2323const req = http.request(options, (res) => {
2324  console.log(`STATUS: ${res.statusCode}`);
2325  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
2326  res.setEncoding('utf8');
2327  res.on('data', (chunk) => {
2328    console.log(`BODY: ${chunk}`);
2329  });
2330  res.on('end', () => {
2331    console.log('No more data in response.');
2332  });
2333});
2334
2335req.on('error', (e) => {
2336  console.error(`problem with request: ${e.message}`);
2337});
2338
2339// Write data to request body
2340req.write(postData);
2341req.end();
2342```
2343
2344In the example `req.end()` was called. With `http.request()` one
2345must always call `req.end()` to signify the end of the request -
2346even if there is no data being written to the request body.
2347
2348If any error is encountered during the request (be that with DNS resolution,
2349TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
2350on the returned request object. As with all `'error'` events, if no listeners
2351are registered the error will be thrown.
2352
2353There are a few special headers that should be noted.
2354
2355* Sending a 'Connection: keep-alive' will notify Node.js that the connection to
2356  the server should be persisted until the next request.
2357
2358* Sending a 'Content-Length' header will disable the default chunked encoding.
2359
2360* Sending an 'Expect' header will immediately send the request headers.
2361  Usually, when sending 'Expect: 100-continue', both a timeout and a listener
2362  for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
2363  information.
2364
2365* Sending an Authorization header will override using the `auth` option
2366  to compute basic authentication.
2367
2368Example using a [`URL`][] as `options`:
2369
2370```js
2371const options = new URL('http://abc:xyz@example.com');
2372
2373const req = http.request(options, (res) => {
2374  // ...
2375});
2376```
2377
2378In a successful request, the following events will be emitted in the following
2379order:
2380
2381* `'socket'`
2382* `'response'`
2383  * `'data'` any number of times, on the `res` object
2384    (`'data'` will not be emitted at all if the response body is empty, for
2385    instance, in most redirects)
2386  * `'end'` on the `res` object
2387* `'close'`
2388
2389In the case of a connection error, the following events will be emitted:
2390
2391* `'socket'`
2392* `'error'`
2393* `'close'`
2394
2395If `req.abort()` is called before the connection succeeds, the following events
2396will be emitted in the following order:
2397
2398* `'socket'`
2399* (`req.abort()` called here)
2400* `'abort'`
2401* `'error'` with an error with message `'Error: socket hang up'` and code
2402  `'ECONNRESET'`
2403* `'close'`
2404
2405If `req.abort()` is called after the response is received, the following events
2406will be emitted in the following order:
2407
2408* `'socket'`
2409* `'response'`
2410  * `'data'` any number of times, on the `res` object
2411* (`req.abort()` called here)
2412* `'abort'`
2413* `'aborted'` on the `res` object
2414* `'close'`
2415* `'end'` on the `res` object
2416* `'close'` on the `res` object
2417
2418Setting the `timeout` option or using the `setTimeout()` function will
2419not abort the request or do anything besides add a `'timeout'` event.
2420
2421[`--http-server-default-timeout`]: cli.html#cli_http_server_default_timeout_milliseconds
2422[`--insecure-http-parser`]: cli.html#cli_insecure_http_parser
2423[`--max-http-header-size`]: cli.html#cli_max_http_header_size_size
2424[`'checkContinue'`]: #http_event_checkcontinue
2425[`'request'`]: #http_event_request
2426[`'response'`]: #http_event_response
2427[`'upgrade'`]: #http_event_upgrade
2428[`Agent`]: #http_class_http_agent
2429[`Buffer.byteLength()`]: buffer.html#buffer_static_method_buffer_bytelength_string_encoding
2430[`Duplex`]: stream.html#stream_class_stream_duplex
2431[`TypeError`]: errors.html#errors_class_typeerror
2432[`URL`]: url.html#url_the_whatwg_url_api
2433[`agent.createConnection()`]: #http_agent_createconnection_options_callback
2434[`agent.getName()`]: #http_agent_getname_options
2435[`destroy()`]: #http_agent_destroy
2436[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback
2437[`'finish'`]: #http_event_finish
2438[`getHeader(name)`]: #http_request_getheader_name
2439[`http.Agent`]: #http_class_http_agent
2440[`http.ClientRequest`]: #http_class_http_clientrequest
2441[`http.IncomingMessage`]: #http_class_http_incomingmessage
2442[`http.Server`]: #http_class_http_server
2443[`http.get()`]: #http_http_get_options_callback
2444[`http.globalAgent`]: #http_http_globalagent
2445[`http.request()`]: #http_http_request_options_callback
2446[`message.headers`]: #http_message_headers
2447[`net.Server.close()`]: net.html#net_server_close_callback
2448[`net.Server`]: net.html#net_class_net_server
2449[`net.Socket`]: net.html#net_class_net_socket
2450[`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener
2451[`new URL()`]: url.html#url_new_url_input_base
2452[`removeHeader(name)`]: #http_request_removeheader_name
2453[`request.end()`]: #http_request_end_data_encoding_callback
2454[`request.flushHeaders()`]: #http_request_flushheaders
2455[`request.getHeader()`]: #http_request_getheader_name
2456[`request.setHeader()`]: #http_request_setheader_name_value
2457[`request.setTimeout()`]: #http_request_settimeout_timeout_callback
2458[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
2459[`request.socket`]: #http_request_socket
2460[`request.writableFinished`]: #http_request_writablefinished
2461[`request.writableEnded`]: #http_request_writableended
2462[`request.write(data, encoding)`]: #http_request_write_chunk_encoding_callback
2463[`response.end()`]: #http_response_end_data_encoding_callback
2464[`response.getHeader()`]: #http_response_getheader_name
2465[`response.setHeader()`]: #http_response_setheader_name_value
2466[`response.socket`]: #http_response_socket
2467[`response.writableFinished`]: #http_response_writablefinished
2468[`response.writableEnded`]: #http_response_writableended
2469[`response.write()`]: #http_response_write_chunk_encoding_callback
2470[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
2471[`response.writeContinue()`]: #http_response_writecontinue
2472[`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
2473[`server.listen()`]: net.html#net_server_listen
2474[`server.timeout`]: #http_server_timeout
2475[`setHeader(name, value)`]: #http_request_setheader_name_value
2476[`socket.connect()`]: net.html#net_socket_connect_options_connectlistener
2477[`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
2478[`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
2479[`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
2480[`socket.unref()`]: net.html#net_socket_unref
2481[`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
2482[`HPE_HEADER_OVERFLOW`]: errors.html#errors_hpe_header_overflow
2483[`writable.cork()`]: stream.html#stream_writable_cork
2484[`writable.uncork()`]: stream.html#stream_writable_uncork
2485