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