05221ed23cff9146c6a74d341543a5111849a42f
[platform/upstream/nodejs.git] / doc / api / http.markdown
1 # HTTP
2
3     Stability: 2 - Stable
4
5 To use the HTTP server and client one must `require('http')`.
6
7 The HTTP interfaces in Node.js are designed to support many features
8 of the protocol which have been traditionally difficult to use.
9 In particular, large, possibly chunk-encoded, messages. The interface is
10 careful to never buffer entire requests or responses--the
11 user is able to stream data.
12
13 HTTP message headers are represented by an object like this:
14
15     { 'content-length': '123',
16       'content-type': 'text/plain',
17       'connection': 'keep-alive',
18       'host': 'mysite.com',
19       'accept': '*/*' }
20
21 Keys are lowercased. Values are not modified.
22
23 In order to support the full spectrum of possible HTTP applications, Node.js's
24 HTTP API is very low-level. It deals with stream handling and message
25 parsing only. It parses a message into headers and body but it does not
26 parse the actual headers or the body.
27
28 See [`message.headers`][] for details on how duplicate headers are handled.
29
30 The raw headers as they were received are retained in the `rawHeaders`
31 property, which is an array of `[key, value, key2, value2, ...]`.  For
32 example, the previous message header object might have a `rawHeaders`
33 list like the following:
34
35     [ 'ConTent-Length', '123456',
36       'content-LENGTH', '123',
37       'content-type', 'text/plain',
38       'CONNECTION', 'keep-alive',
39       'Host', 'mysite.com',
40       'accepT', '*/*' ]
41
42 ## Class: http.Agent
43
44 The HTTP Agent is used for pooling sockets used in HTTP client
45 requests.
46
47 The HTTP Agent also defaults client requests to using
48 Connection:keep-alive. If no pending HTTP requests are waiting on a
49 socket to become free the socket is closed. This means that Node.js's
50 pool has the benefit of keep-alive when under load but still does not
51 require developers to manually close the HTTP clients using
52 KeepAlive.
53
54 If you opt into using HTTP KeepAlive, you can create an Agent object
55 with that flag set to `true`.  (See the [constructor options][] below.)
56 Then, the Agent will keep unused sockets in a pool for later use.  They
57 will be explicitly marked so as to not keep the Node.js process running.
58 However, it is still a good idea to explicitly [`destroy()`][] KeepAlive
59 agents when they are no longer in use, so that the Sockets will be shut
60 down.
61
62 Sockets are removed from the agent's pool when the socket emits either
63 a `'close'` event or a special `'agentRemove'` event. This means that if
64 you intend to keep one HTTP request open for a long time and don't
65 want it to stay in the pool you can do something along the lines of:
66
67     http.get(options, (res) => {
68       // Do stuff
69     }).on('socket', (socket) => {
70       socket.emit('agentRemove');
71     });
72
73 Alternatively, you could just opt out of pooling entirely using
74 `agent:false`:
75
76     http.get({
77       hostname: 'localhost',
78       port: 80,
79       path: '/',
80       agent: false  // create a new agent just for this one request
81     }, (res) => {
82       // Do stuff with response
83     })
84
85 ### new Agent([options])
86
87 * `options` {Object} Set of configurable options to set on the agent.
88   Can have the following fields:
89   * `keepAlive` {Boolean} Keep sockets around in a pool to be used by
90     other requests in the future. Default = `false`
91   * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often
92     to send TCP KeepAlive packets over sockets being kept alive.
93     Default = `1000`.  Only relevant if `keepAlive` is set to `true`.
94   * `maxSockets` {Number} Maximum number of sockets to allow per
95     host.  Default = `Infinity`.
96   * `maxFreeSockets` {Number} Maximum number of sockets to leave open
97     in a free state.  Only relevant if `keepAlive` is set to `true`.
98     Default = `256`.
99
100 The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
101 of these values set to their respective defaults.
102
103 To configure any of them, you must create your own [`http.Agent`][] object.
104
105 ```javascript
106 const http = require('http');
107 var keepAliveAgent = new http.Agent({ keepAlive: true });
108 options.agent = keepAliveAgent;
109 http.request(options, onResponseCallback);
110 ```
111
112 ### agent.destroy()
113
114 Destroy any sockets that are currently in use by the agent.
115
116 It is usually not necessary to do this.  However, if you are using an
117 agent with KeepAlive enabled, then it is best to explicitly shut down
118 the agent when you know that it will no longer be used.  Otherwise,
119 sockets may hang open for quite a long time before the server
120 terminates them.
121
122 ### agent.freeSockets
123
124 An object which contains arrays of sockets currently awaiting use by
125 the Agent when HTTP KeepAlive is used.  Do not modify.
126
127 ### agent.getName(options)
128
129 Get a unique name for a set of request options, to determine whether a
130 connection can be reused.  In the http agent, this returns
131 `host:port:localAddress`.  In the https agent, the name includes the
132 CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
133 socket reusability.
134
135 ### agent.maxFreeSockets
136
137 By default set to 256.  For Agents supporting HTTP KeepAlive, this
138 sets the maximum number of sockets that will be left open in the free
139 state.
140
141 ### agent.maxSockets
142
143 By default set to Infinity. Determines how many concurrent sockets the agent
144 can have open per origin. Origin is either a 'host:port' or
145 'host:port:localAddress' combination.
146
147 ### agent.requests
148
149 An object which contains queues of requests that have not yet been assigned to
150 sockets. Do not modify.
151
152 ### agent.sockets
153
154 An object which contains arrays of sockets currently in use by the
155 Agent.  Do not modify.
156
157 ## Class: http.ClientRequest
158
159 This object is created internally and returned from [`http.request()`][].  It
160 represents an _in-progress_ request whose header has already been queued.  The
161 header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
162 `removeHeader(name)` API.  The actual header will be sent along with the first
163 data chunk or when closing the connection.
164
165 To get the response, add a listener for `'response'` to the request object.
166 `'response'` will be emitted from the request object when the response
167 headers have been received.  The `'response'` event is executed with one
168 argument which is an instance of [`http.IncomingMessage`][].
169
170 During the `'response'` event, one can add listeners to the
171 response object; particularly to listen for the `'data'` event.
172
173 If no `'response'` handler is added, then the response will be
174 entirely discarded.  However, if you add a `'response'` event handler,
175 then you **must** consume the data from the response object, either by
176 calling `response.read()` whenever there is a `'readable'` event, or
177 by adding a `'data'` handler, or by calling the `.resume()` method.
178 Until the data is consumed, the `'end'` event will not fire.  Also, until
179 the data is read it will consume memory that can eventually lead to a
180 'process out of memory' error.
181
182 Note: Node.js does not check whether Content-Length and the length of the body
183 which has been transmitted are equal or not.
184
185 The request implements the [Writable Stream][] interface. This is an
186 [`EventEmitter`][] with the following events:
187
188 ### Event: 'abort'
189
190 `function () { }`
191
192 Emitted when the request has been aborted by the client. This event is only
193 emitted on the first call to `abort()`.
194
195 ### Event: 'connect'
196
197 `function (response, socket, head) { }`
198
199 Emitted each time a server responds to a request with a `CONNECT` method. If this
200 event isn't being listened for, clients receiving a `CONNECT` method will have
201 their connections closed.
202
203 A client server pair that show you how to listen for the `'connect'` event.
204
205     const http = require('http');
206     const net = require('net');
207     const url = require('url');
208
209     // Create an HTTP tunneling proxy
210     var proxy = http.createServer( (req, res) => {
211       res.writeHead(200, {'Content-Type': 'text/plain'});
212       res.end('okay');
213     });
214     proxy.on('connect', (req, cltSocket, head) => {
215       // connect to an origin server
216       var srvUrl = url.parse(`http://${req.url}`);
217       var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
218         cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
219                         'Proxy-agent: Node.js-Proxy\r\n' +
220                         '\r\n');
221         srvSocket.write(head);
222         srvSocket.pipe(cltSocket);
223         cltSocket.pipe(srvSocket);
224       });
225     });
226
227     // now that proxy is running
228     proxy.listen(1337, '127.0.0.1', () => {
229
230       // make a request to a tunneling proxy
231       var options = {
232         port: 1337,
233         hostname: '127.0.0.1',
234         method: 'CONNECT',
235         path: 'www.google.com:80'
236       };
237
238       var req = http.request(options);
239       req.end();
240
241       req.on('connect', (res, socket, head) => {
242         console.log('got connected!');
243
244         // make a request over an HTTP tunnel
245         socket.write('GET / HTTP/1.1\r\n' +
246                      'Host: www.google.com:80\r\n' +
247                      'Connection: close\r\n' +
248                      '\r\n');
249         socket.on('data', (chunk) => {
250           console.log(chunk.toString());
251         });
252         socket.on('end', () => {
253           proxy.close();
254         });
255       });
256     });
257
258 ### Event: 'continue'
259
260 `function () { }`
261
262 Emitted when the server sends a '100 Continue' HTTP response, usually because
263 the request contained 'Expect: 100-continue'. This is an instruction that
264 the client should send the request body.
265
266 ### Event: 'response'
267
268 `function (response) { }`
269
270 Emitted when a response is received to this request. This event is emitted only
271 once. The `response` argument will be an instance of [`http.IncomingMessage`][].
272
273 Options:
274
275 - `host`: A domain name or IP address of the server to issue the request to.
276 - `port`: Port of remote server.
277 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath)
278
279 ### Event: 'socket'
280
281 `function (socket) { }`
282
283 Emitted after a socket is assigned to this request.
284
285 ### Event: 'upgrade'
286
287 `function (response, socket, head) { }`
288
289 Emitted each time a server responds to a request with an upgrade. If this
290 event isn't being listened for, clients receiving an upgrade header will have
291 their connections closed.
292
293 A client server pair that show you how to listen for the `'upgrade'` event.
294
295     const http = require('http');
296
297     // Create an HTTP server
298     var srv = http.createServer( (req, res) => {
299       res.writeHead(200, {'Content-Type': 'text/plain'});
300       res.end('okay');
301     });
302     srv.on('upgrade', (req, socket, head) => {
303       socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
304                    'Upgrade: WebSocket\r\n' +
305                    'Connection: Upgrade\r\n' +
306                    '\r\n');
307
308       socket.pipe(socket); // echo back
309     });
310
311     // now that server is running
312     srv.listen(1337, '127.0.0.1', () => {
313
314       // make a request
315       var options = {
316         port: 1337,
317         hostname: '127.0.0.1',
318         headers: {
319           'Connection': 'Upgrade',
320           'Upgrade': 'websocket'
321         }
322       };
323
324       var req = http.request(options);
325       req.end();
326
327       req.on('upgrade', (res, socket, upgradeHead) => {
328         console.log('got upgraded!');
329         socket.end();
330         process.exit(0);
331       });
332     });
333
334 ### request.abort()
335
336 Marks the request as aborting. Calling this will cause remaining data
337 in the response to be dropped and the socket to be destroyed.
338
339 ### request.end([data][, encoding][, callback])
340
341 Finishes sending the request. If any parts of the body are
342 unsent, it will flush them to the stream. If the request is
343 chunked, this will send the terminating `'0\r\n\r\n'`.
344
345 If `data` is specified, it is equivalent to calling
346 [`response.write(data, encoding)`][] followed by `request.end(callback)`.
347
348 If `callback` is specified, it will be called when the request stream
349 is finished.
350
351 ### request.flushHeaders()
352
353 Flush the request headers.
354
355 For efficiency reasons, Node.js normally buffers the request headers until you
356 call `request.end()` or write the first chunk of request data.  It then tries
357 hard to pack the request headers and data into a single TCP packet.
358
359 That's usually what you want (it saves a TCP round-trip) but not when the first
360 data isn't sent until possibly much later.  `request.flushHeaders()` lets you bypass
361 the optimization and kickstart the request.
362
363 ### request.setNoDelay([noDelay])
364
365 Once a socket is assigned to this request and is connected
366 [`socket.setNoDelay()`][] will be called.
367
368 ### request.setSocketKeepAlive([enable][, initialDelay])
369
370 Once a socket is assigned to this request and is connected
371 [`socket.setKeepAlive()`][] will be called.
372
373 ### request.setTimeout(timeout[, callback])
374
375 Once a socket is assigned to this request and is connected
376 [`socket.setTimeout()`][] will be called.
377
378 * `timeout` {Number} Milliseconds before a request is considered to be timed out.
379 * `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.
380
381 ### request.write(chunk[, encoding][, callback])
382
383 Sends a chunk of the body.  By calling this method
384 many times, the user can stream a request body to a
385 server--in that case it is suggested to use the
386 `['Transfer-Encoding', 'chunked']` header line when
387 creating the request.
388
389 The `chunk` argument should be a [`Buffer`][] or a string.
390
391 The `encoding` argument is optional and only applies when `chunk` is a string.
392 Defaults to `'utf8'`.
393
394 The `callback` argument is optional and will be called when this chunk of data
395 is flushed.
396
397 Returns `request`.
398
399 ## Class: http.Server
400
401 This class inherits from [`net.Server`][] and has the following additional events:
402
403 ### Event: 'checkContinue'
404
405 `function (request, response) { }`
406
407 Emitted each time a request with an http Expect: 100-continue is received.
408 If this event isn't listened for, the server will automatically respond
409 with a 100 Continue as appropriate.
410
411 Handling this event involves calling [`response.writeContinue()`][] if the client
412 should continue to send the request body, or generating an appropriate HTTP
413 response (e.g., 400 Bad Request) if the client should not continue to send the
414 request body.
415
416 Note that when this event is emitted and handled, the `'request'` event will
417 not be emitted.
418
419 ### Event: 'clientError'
420
421 `function (exception, socket) { }`
422
423 If a client connection emits an `'error'` event, it will be forwarded here.
424
425 `socket` is the [`net.Socket`][] object that the error originated from.
426
427 ### Event: 'close'
428
429 `function () { }`
430
431 Emitted when the server closes.
432
433 ### Event: 'connect'
434
435 `function (request, socket, head) { }`
436
437 Emitted each time a client requests a http `CONNECT` method. If this event isn't
438 listened for, then clients requesting a `CONNECT` method will have their
439 connections closed.
440
441 * `request` is the arguments for the http request, as it is in the request
442   event.
443 * `socket` is the network socket between the server and client.
444 * `head` is an instance of Buffer, the first packet of the tunneling stream,
445   this may be empty.
446
447 After this event is emitted, the request's socket will not have a `'data'`
448 event listener, meaning you will need to bind to it in order to handle data
449 sent to the server on that socket.
450
451 ### Event: 'connection'
452
453 `function (socket) { }`
454
455 When a new TCP stream is established. `socket` is an object of type
456 [`net.Socket`][]. Usually users will not want to access this event. In
457 particular, the socket will not emit `'readable'` events because of how
458 the protocol parser attaches to the socket. The `socket` can also be
459 accessed at `request.connection`.
460
461 ### Event: 'request'
462
463 `function (request, response) { }`
464
465 Emitted each time there is a request. Note that there may be multiple requests
466 per connection (in the case of keep-alive connections).
467  `request` is an instance of [`http.IncomingMessage`][] and `response` is
468 an instance of [`http.ServerResponse`][].
469
470 ### Event: 'upgrade'
471
472 `function (request, socket, head) { }`
473
474 Emitted each time a client requests a http upgrade. If this event isn't
475 listened for, then clients requesting an upgrade will have their connections
476 closed.
477
478 * `request` is the arguments for the http request, as it is in the request
479   event.
480 * `socket` is the network socket between the server and client.
481 * `head` is an instance of Buffer, the first packet of the upgraded stream,
482   this may be empty.
483
484 After this event is emitted, the request's socket will not have a `'data'`
485 event listener, meaning you will need to bind to it in order to handle data
486 sent to the server on that socket.
487
488 ### server.close([callback])
489
490 Stops the server from accepting new connections.  See [`net.Server.close()`][].
491
492 ### server.listen(handle[, callback])
493
494 * `handle` {Object}
495 * `callback` {Function}
496
497 The `handle` object can be set to either a server or socket (anything
498 with an underlying `_handle` member), or a `{fd: <n>}` object.
499
500 This will cause the server to accept connections on the specified
501 handle, but it is presumed that the file descriptor or handle has
502 already been bound to a port or domain socket.
503
504 Listening on a file descriptor is not supported on Windows.
505
506 This function is asynchronous. The last parameter `callback` will be added as
507 a listener for the `'listening'` event. See also [`net.Server.listen()`][].
508
509 Returns `server`.
510
511 ### server.listen(path[, callback])
512
513 Start a UNIX socket server listening for connections on the given `path`.
514
515 This function is asynchronous. The last parameter `callback` will be added as
516 a listener for the `'listening'` event.  See also [`net.Server.listen(path)`][].
517
518 ### server.listen(port[, hostname][, backlog][, callback])
519
520 Begin accepting connections on the specified `port` and `hostname`. If the
521 `hostname` is omitted, the server will accept connections on any IPv6 address
522 (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
523 port value of zero will assign a random port.
524
525 To listen to a unix socket, supply a filename instead of port and hostname.
526
527 Backlog is the maximum length of the queue of pending connections.
528 The actual length will be determined by your OS through sysctl settings such as
529 `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
530 parameter is 511 (not 512).
531
532 This function is asynchronous. The last parameter `callback` will be added as
533 a listener for the `'listening'` event.  See also [`net.Server.listen(port)`][].
534
535 ### server.maxHeadersCount
536
537 Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
538 no limit will be applied.
539
540 ### server.setTimeout(msecs, callback)
541
542 * `msecs` {Number}
543 * `callback` {Function}
544
545 Sets the timeout value for sockets, and emits a `'timeout'` event on
546 the Server object, passing the socket as an argument, if a timeout
547 occurs.
548
549 If there is a `'timeout'` event listener on the Server object, then it
550 will be called with the timed-out socket as an argument.
551
552 By default, the Server's timeout value is 2 minutes, and sockets are
553 destroyed automatically if they time out.  However, if you assign a
554 callback to the Server's `'timeout'` event, then you are responsible
555 for handling socket timeouts.
556
557 Returns `server`.
558
559 ### server.timeout
560
561 * {Number} Default = 120000 (2 minutes)
562
563 The number of milliseconds of inactivity before a socket is presumed
564 to have timed out.
565
566 Note that the socket timeout logic is set up on connection, so
567 changing this value only affects *new* connections to the server, not
568 any existing connections.
569
570 Set to 0 to disable any kind of automatic timeout behavior on incoming
571 connections.
572
573 ## Class: http.ServerResponse
574
575 This object is created internally by a HTTP server--not by the user. It is
576 passed as the second parameter to the `'request'` event.
577
578 The response implements the [Writable Stream][] interface. This is an
579 [`EventEmitter`][] with the following events:
580
581 ### Event: 'close'
582
583 `function () { }`
584
585 Indicates that the underlying connection was terminated before
586 [`response.end()`][] was called or able to flush.
587
588 ### Event: 'finish'
589
590 `function () { }`
591
592 Emitted when the response has been sent. More specifically, this event is
593 emitted when the last segment of the response headers and body have been
594 handed off to the operating system for transmission over the network. It
595 does not imply that the client has received anything yet.
596
597 After this event, no more events will be emitted on the response object.
598
599 ### response.addTrailers(headers)
600
601 This method adds HTTP trailing headers (a header but at the end of the
602 message) to the response.
603
604 Trailers will **only** be emitted if chunked encoding is used for the
605 response; if it is not (e.g., if the request was HTTP/1.0), they will
606 be silently discarded.
607
608 Note that HTTP requires the `Trailer` header to be sent if you intend to
609 emit trailers, with a list of the header fields in its value. E.g.,
610
611     response.writeHead(200, { 'Content-Type': 'text/plain',
612                               'Trailer': 'Content-MD5' });
613     response.write(fileData);
614     response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
615     response.end();
616
617 Attempting to set a header field name or value that contains invalid characters
618 will result in a [`TypeError`][] being thrown.
619
620 ### response.end([data][, encoding][, callback])
621
622 This method signals to the server that all of the response headers and body
623 have been sent; that server should consider this message complete.
624 The method, `response.end()`, MUST be called on each response.
625
626 If `data` is specified, it is equivalent to calling
627 [`response.write(data, encoding)`][] followed by `response.end(callback)`.
628
629 If `callback` is specified, it will be called when the response stream
630 is finished.
631
632 ### response.finished
633
634 Boolean value that indicates whether the response has completed. Starts
635 as `false`. After [`response.end()`][] executes, the value will be `true`.
636
637 ### response.getHeader(name)
638
639 Reads out a header that's already been queued but not sent to the client.  Note
640 that the name is case insensitive.  This can only be called before headers get
641 implicitly flushed.
642
643 Example:
644
645     var contentType = response.getHeader('content-type');
646
647 ### response.headersSent
648
649 Boolean (read-only). True if headers were sent, false otherwise.
650
651 ### response.removeHeader(name)
652
653 Removes a header that's queued for implicit sending.
654
655 Example:
656
657     response.removeHeader('Content-Encoding');
658
659 ### response.sendDate
660
661 When true, the Date header will be automatically generated and sent in
662 the response if it is not already present in the headers. Defaults to true.
663
664 This should only be disabled for testing; HTTP requires the Date header
665 in responses.
666
667 ### response.setHeader(name, value)
668
669 Sets a single header value for implicit headers.  If this header already exists
670 in the to-be-sent headers, its value will be replaced.  Use an array of strings
671 here if you need to send multiple headers with the same name.
672
673 Example:
674
675     response.setHeader('Content-Type', 'text/html');
676
677 or
678
679     response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
680
681 Attempting to set a header field name or value that contains invalid characters
682 will result in a [`TypeError`][] being thrown.
683
684 ### response.setTimeout(msecs, callback)
685
686 * `msecs` {Number}
687 * `callback` {Function}
688
689 Sets the Socket's timeout value to `msecs`.  If a callback is
690 provided, then it is added as a listener on the `'timeout'` event on
691 the response object.
692
693 If no `'timeout'` listener is added to the request, the response, or
694 the server, then sockets are destroyed when they time out.  If you
695 assign a handler on the request, the response, or the server's
696 `'timeout'` events, then it is your responsibility to handle timed out
697 sockets.
698
699 Returns `response`.
700
701 ### response.statusCode
702
703 When using implicit headers (not calling [`response.writeHead()`][] explicitly),
704 this property controls the status code that will be sent to the client when
705 the headers get flushed.
706
707 Example:
708
709     response.statusCode = 404;
710
711 After response header was sent to the client, this property indicates the
712 status code which was sent out.
713
714 ### response.statusMessage
715
716 When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property
717 controls the status message that will be sent to the client when the headers get
718 flushed. If this is left as `undefined` then the standard message for the status
719 code will be used.
720
721 Example:
722
723     response.statusMessage = 'Not found';
724
725 After response header was sent to the client, this property indicates the
726 status message which was sent out.
727
728 ### response.write(chunk[, encoding][, callback])
729
730 If this method is called and [`response.writeHead()`][] has not been called,
731 it will switch to implicit header mode and flush the implicit headers.
732
733 This sends a chunk of the response body. This method may
734 be called multiple times to provide successive parts of the body.
735
736 `chunk` can be a string or a buffer. If `chunk` is a string,
737 the second parameter specifies how to encode it into a byte stream.
738 By default the `encoding` is `'utf8'`. The last parameter `callback`
739 will be called when this chunk of data is flushed.
740
741 **Note**: This is the raw HTTP body and has nothing to do with
742 higher-level multi-part body encodings that may be used.
743
744 The first time [`response.write()`][] is called, it will send the buffered
745 header information and the first body to the client. The second time
746 [`response.write()`][] is called, Node.js assumes you're going to be streaming
747 data, and sends that separately. That is, the response is buffered up to the
748 first chunk of body.
749
750 Returns `true` if the entire data was flushed successfully to the kernel
751 buffer. Returns `false` if all or part of the data was queued in user memory.
752 `'drain'` will be emitted when the buffer is free again.
753
754 ### response.writeContinue()
755
756 Sends a HTTP/1.1 100 Continue message to the client, indicating that
757 the request body should be sent. See the [`'checkContinue'`][] event on `Server`.
758
759 ### response.writeHead(statusCode[, statusMessage][, headers])
760
761 Sends a response header to the request. The status code is a 3-digit HTTP
762 status code, like `404`. The last argument, `headers`, are the response headers.
763 Optionally one can give a human-readable `statusMessage` as the second
764 argument.
765
766 Example:
767
768     var body = 'hello world';
769     response.writeHead(200, {
770       'Content-Length': body.length,
771       'Content-Type': 'text/plain' });
772
773 This method must only be called once on a message and it must
774 be called before [`response.end()`][] is called.
775
776 If you call [`response.write()`][] or [`response.end()`][] before calling this,
777 the implicit/mutable headers will be calculated and call this function for you.
778
779 Note that Content-Length is given in bytes not characters. The above example
780 works because the string `'hello world'` contains only single byte characters.
781 If the body contains higher coded characters then `Buffer.byteLength()`
782 should be used to determine the number of bytes in a given encoding.
783 And Node.js does not check whether Content-Length and the length of the body
784 which has been transmitted are equal or not.
785
786 Attempting to set a header field name or value that contains invalid characters
787 will result in a [`TypeError`][] being thrown.
788
789 ## Class: http.IncomingMessage
790
791 An `IncomingMessage` object is created by [`http.Server`][] or
792 [`http.ClientRequest`][] and passed as the first argument to the `'request'`
793 and `'response'` event respectively. It may be used to access response status,
794 headers and data.
795
796 It implements the [Readable Stream][] interface, as well as the
797 following additional events, methods, and properties.
798
799 ### Event: 'close'
800
801 `function () { }`
802
803 Indicates that the underlying connection was closed.
804 Just like `'end'`, this event occurs only once per response.
805
806 ### message.headers
807
808 The request/response headers object.
809
810 Key-value pairs of header names and values. Header names are lower-cased.
811 Example:
812
813     // Prints something like:
814     //
815     // { 'user-agent': 'curl/7.22.0',
816     //   host: '127.0.0.1:8000',
817     //   accept: '*/*' }
818     console.log(request.headers);
819
820 Duplicates in raw headers are handled in the following ways, depending on the
821 header name:
822
823 * Duplicates of `age`, `authorization`, `content-length`, `content-type`,
824 `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
825 `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
826 `retry-after`, or `user-agent` are discarded.
827 * `set-cookie` is always an array. Duplicates are added to the array.
828 * For all other headers, the values are joined together with ', '.
829
830 ### message.httpVersion
831
832 In case of server request, the HTTP version sent by the client. In the case of
833 client response, the HTTP version of the connected-to server.
834 Probably either `'1.1'` or `'1.0'`.
835
836 Also `response.httpVersionMajor` is the first integer and
837 `response.httpVersionMinor` is the second.
838
839 ### message.method
840
841 **Only valid for request obtained from [`http.Server`][].**
842
843 The request method as a string. Read only. Example:
844 `'GET'`, `'DELETE'`.
845
846 ### message.rawHeaders
847
848 The raw request/response headers list exactly as they were received.
849
850 Note that the keys and values are in the same list.  It is *not* a
851 list of tuples.  So, the even-numbered offsets are key values, and the
852 odd-numbered offsets are the associated values.
853
854 Header names are not lowercased, and duplicates are not merged.
855
856     // Prints something like:
857     //
858     // [ 'user-agent',
859     //   'this is invalid because there can be only one',
860     //   'User-Agent',
861     //   'curl/7.22.0',
862     //   'Host',
863     //   '127.0.0.1:8000',
864     //   'ACCEPT',
865     //   '*/*' ]
866     console.log(request.rawHeaders);
867
868 ### message.rawTrailers
869
870 The raw request/response trailer keys and values exactly as they were
871 received.  Only populated at the `'end'` event.
872
873 ### message.setTimeout(msecs, callback)
874
875 * `msecs` {Number}
876 * `callback` {Function}
877
878 Calls `message.connection.setTimeout(msecs, callback)`.
879
880 Returns `message`.
881
882 ### message.statusCode
883
884 **Only valid for response obtained from [`http.ClientRequest`][].**
885
886 The 3-digit HTTP response status code. E.G. `404`.
887
888 ### message.statusMessage
889
890 **Only valid for response obtained from [`http.ClientRequest`][].**
891
892 The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
893
894 ### message.socket
895
896 The [`net.Socket`][] object associated with the connection.
897
898 With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
899 client's authentication details.
900
901 ### message.trailers
902
903 The request/response trailers object. Only populated at the `'end'` event.
904
905 ### message.url
906
907 **Only valid for request obtained from [`http.Server`][].**
908
909 Request URL string. This contains only the URL that is
910 present in the actual HTTP request. If the request is:
911
912     GET /status?name=ryan HTTP/1.1\r\n
913     Accept: text/plain\r\n
914     \r\n
915
916 Then `request.url` will be:
917
918     '/status?name=ryan'
919
920 If you would like to parse the URL into its parts, you can use
921 `require('url').parse(request.url)`.  Example:
922
923     node> require('url').parse('/status?name=ryan')
924     { href: '/status?name=ryan',
925       search: '?name=ryan',
926       query: 'name=ryan',
927       pathname: '/status' }
928
929 If you would like to extract the params from the query string,
930 you can use the `require('querystring').parse` function, or pass
931 `true` as the second argument to `require('url').parse`.  Example:
932
933     node> require('url').parse('/status?name=ryan', true)
934     { href: '/status?name=ryan',
935       search: '?name=ryan',
936       query: { name: 'ryan' },
937       pathname: '/status' }
938
939 ## http.METHODS
940
941 * {Array}
942
943 A list of the HTTP methods that are supported by the parser.
944
945 ## http.STATUS_CODES
946
947 * {Object}
948
949 A collection of all the standard HTTP response status codes, and the
950 short description of each.  For example, `http.STATUS_CODES[404] === 'Not
951 Found'`.
952
953 ## http.createClient([port][, host])
954
955     Stability: 0 - Deprecated: Use [`http.request()`][] instead.
956
957 Constructs a new HTTP client. `port` and `host` refer to the server to be
958 connected to.
959
960 ## http.createServer([requestListener])
961
962 Returns a new instance of [`http.Server`][].
963
964 The `requestListener` is a function which is automatically
965 added to the `'request'` event.
966
967 ## http.get(options[, callback])
968
969 Since most requests are GET requests without bodies, Node.js provides this
970 convenience method. The only difference between this method and [`http.request()`][]
971 is that it sets the method to GET and calls `req.end()` automatically.
972
973 Example:
974
975     http.get('http://www.google.com/index.html', (res) => {
976       console.log(`Got response: ${res.statusCode}`);
977       // consume response body
978       res.resume();
979     }).on('error', (e) => {
980       console.log(`Got error: ${e.message}`);
981     });
982
983 ## http.globalAgent
984
985 Global instance of Agent which is used as the default for all http client
986 requests.
987
988 ## http.request(options[, callback])
989
990 Node.js maintains several connections per server to make HTTP requests.
991 This function allows one to transparently issue requests.
992
993 `options` can be an object or a string. If `options` is a string, it is
994 automatically parsed with [`url.parse()`][].
995
996 Options:
997
998 - `protocol`: Protocol to use. Defaults to `'http:'`.
999 - `host`: A domain name or IP address of the server to issue the request to.
1000   Defaults to `'localhost'`.
1001 - `hostname`: Alias for `host`. To support [`url.parse()`][] `hostname` is
1002   preferred over `host`.
1003 - `family`: IP address family to use when resolving `host` and `hostname`.
1004   Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be
1005   used.
1006 - `port`: Port of remote server. Defaults to 80.
1007 - `localAddress`: Local interface to bind for network connections.
1008 - `socketPath`: Unix Domain Socket (use one of host:port or socketPath).
1009 - `method`: A string specifying the HTTP request method. Defaults to `'GET'`.
1010 - `path`: Request path. Defaults to `'/'`. Should include query string if any.
1011   E.G. `'/index.html?page=12'`. An exception is thrown when the request path
1012   contains illegal characters. Currently, only spaces are rejected but that
1013   may change in the future.
1014 - `headers`: An object containing request headers.
1015 - `auth`: Basic authentication i.e. `'user:password'` to compute an
1016   Authorization header.
1017 - `agent`: Controls [`Agent`][] behavior. When an Agent is used request will
1018   default to `Connection: keep-alive`. Possible values:
1019  - `undefined` (default): use [`http.globalAgent`][] for this host and port.
1020  - `Agent` object: explicitly use the passed in `Agent`.
1021  - `false`: opts out of connection pooling with an Agent, defaults request to
1022    `Connection: close`.
1023
1024 The optional `callback` parameter will be added as a one time listener for
1025 the `'response'` event.
1026
1027 `http.request()` returns an instance of the [`http.ClientRequest`][]
1028 class. The `ClientRequest` instance is a writable stream. If one needs to
1029 upload a file with a POST request, then write to the `ClientRequest` object.
1030
1031 Example:
1032
1033     var postData = querystring.stringify({
1034       'msg' : 'Hello World!'
1035     });
1036
1037     var options = {
1038       hostname: 'www.google.com',
1039       port: 80,
1040       path: '/upload',
1041       method: 'POST',
1042       headers: {
1043         'Content-Type': 'application/x-www-form-urlencoded',
1044         'Content-Length': postData.length
1045       }
1046     };
1047
1048     var req = http.request(options, (res) => {
1049       console.log(`STATUS: ${res.statusCode}`);
1050       console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
1051       res.setEncoding('utf8');
1052       res.on('data', (chunk) => {
1053         console.log(`BODY: ${chunk}`);
1054       });
1055       res.on('end', () => {
1056         console.log('No more data in response.')
1057       })
1058     });
1059
1060     req.on('error', (e) => {
1061       console.log(`problem with request: ${e.message}`);
1062     });
1063
1064     // write data to request body
1065     req.write(postData);
1066     req.end();
1067
1068 Note that in the example `req.end()` was called. With `http.request()` one
1069 must always call `req.end()` to signify that you're done with the request -
1070 even if there is no data being written to the request body.
1071
1072 If any error is encountered during the request (be that with DNS resolution,
1073 TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
1074 on the returned request object. As with all `'error'` events, if no listeners
1075 are registered the error will be thrown.
1076
1077 There are a few special headers that should be noted.
1078
1079 * Sending a 'Connection: keep-alive' will notify Node.js that the connection to
1080   the server should be persisted until the next request.
1081
1082 * Sending a 'Content-length' header will disable the default chunked encoding.
1083
1084 * Sending an 'Expect' header will immediately send the request headers.
1085   Usually, when sending 'Expect: 100-continue', you should both set a timeout
1086   and listen for the `'continue'` event. See RFC2616 Section 8.2.3 for more
1087   information.
1088
1089 * Sending an Authorization header will override using the `auth` option
1090   to compute basic authentication.
1091
1092 [`'checkContinue'`]: #http_event_checkcontinue
1093 [`'listening'`]: net.html#net_event_listening
1094 [`'response'`]: #http_event_response
1095 [`Agent`]: #http_class_http_agent
1096 [`Buffer`]: buffer.html#buffer_buffer
1097 [`destroy()`]: #http_agent_destroy
1098 [`EventEmitter`]: events.html#events_class_events_eventemitter
1099 [`http.Agent`]: #http_class_http_agent
1100 [`http.ClientRequest`]: #http_class_http_clientrequest
1101 [`http.globalAgent`]: #http_http_globalagent
1102 [`http.IncomingMessage`]: #http_http_incomingmessage
1103 [`http.request()`]: #http_http_request_options_callback
1104 [`http.Server`]: #http_class_http_server
1105 [`http.ServerResponse`]: #http_class_http_serverresponse
1106 [`message.headers`]: #http_message_headers
1107 [`net.Server`]: net.html#net_class_net_server
1108 [`net.Server.close()`]: net.html#net_server_close_callback
1109 [`net.Server.listen()`]: net.html#net_server_listen_handle_callback
1110 [`net.Server.listen(path)`]: net.html#net_server_listen_path_callback
1111 [`net.Server.listen(port)`]: net.html#net_server_listen_port_hostname_backlog_callback
1112 [`net.Socket`]: net.html#net_class_net_socket
1113 [`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
1114 [`response.end()`]: #http_response_end_data_encoding_callback
1115 [`response.write()`]: #http_response_write_chunk_encoding_callback
1116 [`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
1117 [`response.writeContinue()`]: #http_response_writecontinue
1118 [`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
1119 [`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
1120 [`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
1121 [`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
1122 [`stream.setEncoding()`]: stream.html#stream_stream_setencoding_encoding
1123 [`TypeError`]: errors.html#errors_class_typeerror
1124 [`url.parse()`]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
1125 [constructor options]: #http_new_agent_options
1126 [Readable Stream]: stream.html#stream_class_stream_readable
1127 [Writable Stream]: stream.html#stream_class_stream_writable