-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathhttp.md
More file actions
2100 lines (1634 loc) Β· 59.6 KB
/
http.md
File metadata and controls
2100 lines (1634 loc) Β· 59.6 KB
Edit and raw actions
OlderNewer
Β
1
# HTTP
2
3
<!--introduced_in=v0.10.0-->
4
5
> Stability: 2 - Stable
6
7
To use the HTTP server and client one must `require('http')`.
8
9
The HTTP interfaces in Node.js are designed to support many features
10
of the protocol which have been traditionally difficult to use.
11
In particular, large, possibly chunk-encoded, messages. The interface is
12
careful to never buffer entire requests or responses β the
13
user is able to stream data.
14
15
HTTP 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
26
Keys are lowercased. Values are not modified.
27
28
In order to support the full spectrum of possible HTTP applications, Node.js's
29
HTTP API is very low-level. It deals with stream handling and message
30
parsing only. It parses a message into headers and body but it does not
31
parse the actual headers or the body.
32
33
See [`message.headers`][] for details on how duplicate headers are handled.
34
35
The raw headers as they were received are retained in the `rawHeaders`
36
property, which is an array of `[key, value, key2, value2, ...]`. For
37
example, the previous message header object might have a `rawHeaders`
38
list 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
52
added: v0.3.4
53
-->
54
55
An `Agent` is responsible for managing connection persistence
56
and reuse for HTTP clients. It maintains a queue of pending requests
57
for a given host and port, reusing a single socket connection for each
58
until the queue is empty, at which time the socket is either destroyed
59
or put into a pool where it is kept to be used again for requests to the
60
same host and port. Whether it is destroyed or pooled depends on the
61
`keepAlive` [option](#http_new_agent_options).
62
63
Pooled connections have TCP Keep-Alive enabled for them, but servers may
64
still close idle connections, in which case they will be removed from the
65
pool and a new connection will be made when a new HTTP request is made for
66
that host and port. Servers may also refuse to allow multiple requests
67
over the same connection, in which case the connection will have to be
68
remade for every request and cannot be pooled. The `Agent` will still make
69
the requests to that server, but each one will occur over a new connection.
70
71
When a connection is closed by the client or the server, it is removed
72
from the pool. Any unused sockets in the pool will be unrefed so as not
73
to keep the Node.js process running when there are no outstanding requests.
74
(see [`socket.unref()`]).
75
76
It is good practice, to [`destroy()`][] an `Agent` instance when it is no
77
longer in use, because unused sockets consume OS resources.
78
79
Sockets are removed from an agent when the socket emits either
80
a `'close'` event or an `'agentRemove'` event. When intending to keep one
81
HTTP request open for a long time without keeping it in the agent, something
82
like the following may be done:
83
84
```js
85
http.get(options, (res) => {
86
// Do stuff
87
}).on('socket', (socket) => {
88
socket.emit('agentRemove');
89
});
90
```
91
92
An agent may also be used for an individual request. By providing
93
`{agent: false}` as an option to the `http.get()` or `http.request()`
94
functions, a one-time use `Agent` with default options will be used
95
for the client connection.
96
97
`agent:false`:
98
99
```js
100
http.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
112
added: 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. **Default:** `false`.
120
* `keepAliveMsecs` {number} When using the `keepAlive` option, specifies
121
the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay)
122
for TCP Keep-Alive packets. Ignored when the
123
`keepAlive` option is `false` or `undefined`. **Default:** `1000`.
124
* `maxSockets` {number} Maximum number of sockets to allow per
125
host. **Default:** `Infinity`.
126
* `maxFreeSockets` {number} Maximum number of sockets to leave open
127
in a free state. Only relevant if `keepAlive` is set to `true`.
128
**Default:** `256`.
129
130
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
131
of these values set to their respective defaults.
132
133
To configure any of them, a custom [`http.Agent`][] instance must be created.
134
135
```js
136
const http = require('http');
137
const keepAliveAgent = new http.Agent({ keepAlive: true });
138
options.agent = keepAliveAgent;
139
http.request(options, onResponseCallback);
140
```
141
142
### agent.createConnection(options[, callback])
143
<!-- YAML
144
added: v0.11.4
145
-->
146
147
* `options` {Object} Options containing connection details. Check
148
[`net.createConnection()`][] for the format of the options
149
* `callback` {Function} Callback function that receives the created socket
150
* Returns: {net.Socket}
151
152
Produces a socket/stream to be used for HTTP requests.
153
154
By default, this function is the same as [`net.createConnection()`][]. However,
155
custom agents may override this method in case greater flexibility is desired.
156
157
A socket/stream can be supplied in one of two ways: by returning the
158
socket/stream from this function, or by passing the socket/stream to `callback`.
159
160
`callback` has a signature of `(err, stream)`.
161
162
### agent.keepSocketAlive(socket)
163
<!-- YAML
164
added: v8.1.0
165
-->
166
167
* `socket` {net.Socket}
168
169
Called when `socket` is detached from a request and could be persisted by the
170
`Agent`. Default behavior is to:
171
172
```js
173
socket.setKeepAlive(true, this.keepAliveMsecs);
174
socket.unref();
175
return true;
176
```
177
178
This method can be overridden by a particular `Agent` subclass. If this
179
method returns a falsy value, the socket will be destroyed instead of persisting
180
it for use with the next request.
181
182
### agent.reuseSocket(socket, request)
183
<!-- YAML
184
added: v8.1.0
185
-->
186
187
* `socket` {net.Socket}
188
* `request` {http.ClientRequest}
189
190
Called when `socket` is attached to `request` after being persisted because of
191
the keep-alive options. Default behavior is to:
192
193
```js
194
socket.ref();
195
```
196
197
This method can be overridden by a particular `Agent` subclass.
198
199
### agent.destroy()
200
<!-- YAML
201
added: v0.11.4
202
-->
203
204
Destroy any sockets that are currently in use by the agent.
205
206
It is usually not necessary to do this. However, if using an
207
agent with `keepAlive` enabled, then it is best to explicitly shut down
208
the agent when it will no longer be used. Otherwise,
209
sockets may hang open for quite a long time before the server
210
terminates them.
211
212
### agent.freeSockets
213
<!-- YAML
214
added: v0.11.4
215
-->
216
217
* {Object}
218
219
An object which contains arrays of sockets currently awaiting use by
220
the agent when `keepAlive` is enabled. Do not modify.
221
222
### agent.getName(options)
223
<!-- YAML
224
added: v0.11.4
225
-->
226
227
* `options` {Object} A set of options providing information for name generation
228
* `host` {string} A domain name or IP address of the server to issue the
229
request to
230
* `port` {number} Port of remote server
231
* `localAddress` {string} Local interface to bind for network connections
232
when issuing the request
233
* `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.
234
* Returns: {string}
235
236
Get a unique name for a set of request options, to determine whether a
237
connection can be reused. For an HTTP agent, this returns
238
`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent,
239
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
240
that determine socket reusability.
241
242
### agent.maxFreeSockets
243
<!-- YAML
244
added: v0.11.7
245
-->
246
247
* {number}
248
249
By default set to 256. For agents with `keepAlive` enabled, this
250
sets the maximum number of sockets that will be left open in the free
251
state.
252
253
### agent.maxSockets
254
<!-- YAML
255
added: v0.3.6
256
-->
257
258
* {number}
259
260
By default set to `Infinity`. Determines how many concurrent sockets the agent
261
can have open per origin. Origin is the returned value of [`agent.getName()`][].
262
263
### agent.requests
264
<!-- YAML
265
added: v0.5.9
266
-->
267
268
* {Object}
269
270
An object which contains queues of requests that have not yet been assigned to
271
sockets. Do not modify.
272
273
### agent.sockets
274
<!-- YAML
275
added: v0.3.6
276
-->
277
278
* {Object}
279
280
An object which contains arrays of sockets currently in use by the
281
agent. Do not modify.
282
283
## Class: http.ClientRequest
284
<!-- YAML
285
added: v0.1.17
286
-->
287
288
This object is created internally and returned from [`http.request()`][]. It
289
represents an _in-progress_ request whose header has already been queued. The
290
header is still mutable using the [`setHeader(name, value)`][],
291
[`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will
292
be sent along with the first data chunk or when calling [`request.end()`][].
293
294
To get the response, add a listener for [`'response'`][] to the request object.
295
[`'response'`][] will be emitted from the request object when the response
296
headers have been received. The [`'response'`][] event is executed with one
297
argument which is an instance of [`http.IncomingMessage`][].
298
299
During the [`'response'`][] event, one can add listeners to the
300
response object; particularly to listen for the `'data'` event.
301
302
If no [`'response'`][] handler is added, then the response will be
303
entirely discarded. However, if a [`'response'`][] event handler is added,
304
then the data from the response object **must** be consumed, either by
305
calling `response.read()` whenever there is a `'readable'` event, or
306
by adding a `'data'` handler, or by calling the `.resume()` method.
307
Until the data is consumed, the `'end'` event will not fire. Also, until
308
the data is read it will consume memory that can eventually lead to a
309
'process out of memory' error.
310
311
Node.js does not check whether Content-Length and the length of the
312
body which has been transmitted are equal or not.
313
314
The request implements the [Writable Stream][] interface. This is an
315
[`EventEmitter`][] with the following events:
316
317
### Event: 'abort'
318
<!-- YAML
319
added: v1.4.1
320
-->
321
322
Emitted when the request has been aborted by the client. This event is only
323
emitted on the first call to `abort()`.
324
325
### Event: 'connect'
326
<!-- YAML
327
added: v0.7.0
328
-->
329
330
* `response` {http.IncomingMessage}
331
* `socket` {net.Socket}
332
* `head` {Buffer}
333
334
Emitted each time a server responds to a request with a `CONNECT` method. If
335
this event is not being listened for, clients receiving a `CONNECT` method will
336
have their connections closed.
337
338
A client and server pair demonstrating how to listen for the `'connect'` event:
339
340
```js
341
const http = require('http');
342
const net = require('net');
343
const url = require('url');
344
345
// Create an HTTP tunneling proxy
346
const proxy = http.createServer((req, res) => {
347
res.writeHead(200, { 'Content-Type': 'text/plain' });
348
res.end('okay');
349
});
350
proxy.on('connect', (req, cltSocket, head) => {
351
// connect to an origin server
352
const srvUrl = url.parse(`http://${req.url}`);
353
const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
354
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
355
'Proxy-agent: Node.js-Proxy\r\n' +
356
'\r\n');
357
srvSocket.write(head);
358
srvSocket.pipe(cltSocket);
359
cltSocket.pipe(srvSocket);
360
});
361
});
362
363
// now that proxy is running
364
proxy.listen(1337, '127.0.0.1', () => {
365
366
// make a request to a tunneling proxy
367
const options = {
368
port: 1337,
369
hostname: '127.0.0.1',
370
method: 'CONNECT',
371
path: 'www.google.com:80'
372
};
373
374
const req = http.request(options);
375
req.end();
376
377
req.on('connect', (res, socket, head) => {
378
console.log('got connected!');
379
380
// make a request over an HTTP tunnel
381
socket.write('GET / HTTP/1.1\r\n' +
382
'Host: www.google.com:80\r\n' +
383
'Connection: close\r\n' +
384
'\r\n');
385
socket.on('data', (chunk) => {
386
console.log(chunk.toString());
387
});
388
socket.on('end', () => {
389
proxy.close();
390
});
391
});
392
});
393
```
394
395
### Event: 'continue'
396
<!-- YAML
397
added: v0.3.2
398
-->
399
400
Emitted when the server sends a '100 Continue' HTTP response, usually because
401
the request contained 'Expect: 100-continue'. This is an instruction that
402
the client should send the request body.
403
404
### Event: 'information'
405
<!-- YAML
406
added: v10.0.0
407
-->
408
409
Emitted when the server sends a 1xx response (excluding 101 Upgrade). This
410
event is emitted with a callback containing an object with a status code.
411
412
```js
413
const http = require('http');
414
415
const options = {
416
hostname: '127.0.0.1',
417
port: 8080,
418
path: '/length_request'
419
};
420
421
// Make a request
422
const req = http.request(options);
423
req.end();
424
425
req.on('information', (res) => {
426
console.log(`Got information prior to main response: ${res.statusCode}`);
427
});
428
```
429
430
101 Upgrade statuses do not fire this event due to their break from the
431
traditional HTTP request/response chain, such as web sockets, in-place TLS
432
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
433
[`'upgrade'`][] event instead.
434
435
### Event: 'response'
436
<!-- YAML
437
added: v0.1.0
438
-->
439
440
* `response` {http.IncomingMessage}
441
442
Emitted when a response is received to this request. This event is emitted only
443
once.
444
445
### Event: 'socket'
446
<!-- YAML
447
added: v0.5.3
448
-->
449
450
* `socket` {net.Socket}
451
452
Emitted after a socket is assigned to this request.
453
454
### Event: 'timeout'
455
<!-- YAML
456
added: v0.7.8
457
-->
458
459
Emitted when the underlying socket times out from inactivity. This only notifies
460
that the socket has been idle. The request must be aborted manually.
461
462
See also: [`request.setTimeout()`][].
463
464
### Event: 'upgrade'
465
<!-- YAML
466
added: v0.1.94
467
-->
468
469
* `response` {http.IncomingMessage}
470
* `socket` {net.Socket}
471
* `head` {Buffer}
472
473
Emitted each time a server responds to a request with an upgrade. If this
474
event is not being listened for and the response status code is 101 Switching
475
Protocols, clients receiving an upgrade header will have their connections
476
closed.
477
478
A client server pair demonstrating how to listen for the `'upgrade'` event.
479
480
```js
481
const http = require('http');
482
483
// Create an HTTP server
484
const srv = http.createServer((req, res) => {
485
res.writeHead(200, { 'Content-Type': 'text/plain' });
486
res.end('okay');
487
});
488
srv.on('upgrade', (req, socket, head) => {
489
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
490
'Upgrade: WebSocket\r\n' +
491
'Connection: Upgrade\r\n' +
492
'\r\n');
493
494
socket.pipe(socket); // echo back
495
});
496
497
// now that server is running
498
srv.listen(1337, '127.0.0.1', () => {
499
500
// make a request
501
const options = {
502
port: 1337,
503
hostname: '127.0.0.1',
504
headers: {
505
'Connection': 'Upgrade',
506
'Upgrade': 'websocket'
507
}
508
};
509
510
const req = http.request(options);
511
req.end();
512
513
req.on('upgrade', (res, socket, upgradeHead) => {
514
console.log('got upgraded!');
515
socket.end();
516
process.exit(0);
517
});
518
});
519
```
520
521
### request.abort()
522
<!-- YAML
523
added: v0.3.8
524
-->
525
526
Marks the request as aborting. Calling this will cause remaining data
527
in the response to be dropped and the socket to be destroyed.
528
529
### request.aborted
530
<!-- YAML
531
added: v0.11.14
532
changes:
533
- version: REPLACEME
534
pr-url: https://github.com/nodejs/node/pull/20230
535
description: The `aborted` property is no longer a timestamp number.
536
-->
537
538
* {boolean}
539
540
The `request.aborted` property will be `true` if the request has
541
been aborted.
542
543
### request.connection
544
<!-- YAML
545
added: v0.3.0
546
-->
547
548
* {net.Socket}
549
550
See [`request.socket`][].
551
552
### request.end([data[, encoding]][, callback])
553
<!-- YAML
554
added: v0.1.90
555
changes:
556
- version: v10.0.0
557
pr-url: https://github.com/nodejs/node/pull/18780
558
description: This method now returns a reference to `ClientRequest`.
559
-->
560
561
* `data` {string|Buffer}
562
* `encoding` {string}
563
* `callback` {Function}
564
* Returns: {this}
565
566
Finishes sending the request. If any parts of the body are
567
unsent, it will flush them to the stream. If the request is
568
chunked, this will send the terminating `'0\r\n\r\n'`.
569
570
If `data` is specified, it is equivalent to calling
571
[`request.write(data, encoding)`][] followed by `request.end(callback)`.
572
573
If `callback` is specified, it will be called when the request stream
574
is finished.
575
576
### request.flushHeaders()
577
<!-- YAML
578
added: v1.6.0
579
-->
580
581
Flush the request headers.
582
583
For efficiency reasons, Node.js normally buffers the request headers until
584
`request.end()` is called or the first chunk of request data is written. It
585
then tries to pack the request headers and data into a single TCP packet.
586
587
That's usually desired (it saves a TCP round-trip), but not when the first
588
data is not sent until possibly much later. `request.flushHeaders()` bypasses
589
the optimization and kickstarts the request.
590
591
### request.getHeader(name)
592
<!-- YAML
593
added: v1.6.0
594
-->
595
596
* `name` {string}
597
* Returns: {any}
598
599
Reads out a header on the request. Note that the name is case insensitive.
600
The type of the return value depends on the arguments provided to
601
[`request.setHeader()`][].
602
603
Example:
604
```js
605
request.setHeader('content-type', 'text/html');
606
request.setHeader('Content-Length', Buffer.byteLength(body));
607
request.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
608
const contentType = request.getHeader('Content-Type');
609
// contentType is 'text/html'
610
const contentLength = request.getHeader('Content-Length');
611
// contentLength is of type number
612
const setCookie = request.getHeader('set-cookie');
613
// setCookie is of type string[]
614
```
615
616
### request.maxHeadersCount
617
618
* {number} **Default:** `2000`
619
620
Limits maximum response headers count. If set to 0, no limit will be applied.
621
622
### request.removeHeader(name)
623
<!-- YAML
624
added: v1.6.0
625
-->
626
627
* `name` {string}
628
629
Removes a header that's already defined into headers object.
630
631
Example:
632
```js
633
request.removeHeader('Content-Type');
634
```
635
636
### request.setHeader(name, value)
637
<!-- YAML
638
added: v1.6.0
639
-->
640
641
* `name` {string}
642
* `value` {any}
643
644
Sets a single header value for headers object. If this header already exists in
645
the to-be-sent headers, its value will be replaced. Use an array of strings
646
here to send multiple headers with the same name. Non-string values will be
647
stored without modification. Therefore, [`request.getHeader()`][] may return
648
non-string values. However, the non-string values will be converted to strings
649
for network transmission.
650
651
Example:
652
```js
653
request.setHeader('Content-Type', 'application/json');
654
```
655
656
or
657
658
```js
659
request.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
660
```
661
662
### request.setNoDelay([noDelay])
663
<!-- YAML
664
added: v0.5.9
665
-->
666
667
* `noDelay` {boolean}
668
669
Once a socket is assigned to this request and is connected
670
[`socket.setNoDelay()`][] will be called.
671
672
### request.setSocketKeepAlive([enable][, initialDelay])
673
<!-- YAML
674
added: v0.5.9
675
-->
676
677
* `enable` {boolean}
678
* `initialDelay` {number}
679
680
Once a socket is assigned to this request and is connected
681
[`socket.setKeepAlive()`][] will be called.
682
683
### request.setTimeout(timeout[, callback])
684
<!-- YAML
685
added: v0.5.9
686
-->
687
688
* `timeout` {number} Milliseconds before a request times out.
689
* `callback` {Function} Optional function to be called when a timeout occurs.
690
Same as binding to the `'timeout'` event.
691
* Returns: {http.ClientRequest}
692
693
Once a socket is assigned to this request and is connected
694
[`socket.setTimeout()`][] will be called.
695
696
### request.socket
697
<!-- YAML
698
added: v0.3.0
699
-->
700
701
* {net.Socket}
702
703
Reference to the underlying socket. Usually users will not want to access
704
this property. In particular, the socket will not emit `'readable'` events
705
because of how the protocol parser attaches to the socket. The `socket`
706
may also be accessed via `request.connection`.
707
708
Example:
709
710
```js
711
const http = require('http');
712
const options = {
713
host: 'www.google.com',
714
};
715
const req = http.get(options);
716
req.end();
717
req.once('response', (res) => {
718
const ip = req.socket.localAddress;
719
const port = req.socket.localPort;
720
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
721
// consume response object
722
});
723
```
724
725
### request.write(chunk[, encoding][, callback])
726
<!-- YAML
727
added: v0.1.29
728
-->
729
730
* `chunk` {string|Buffer}
731
* `encoding` {string}
732
* `callback` {Function}
733
* Returns: {boolean}
734
735
Sends a chunk of the body. By calling this method
736
many times, a request body can be sent to a
737
server β in that case it is suggested to use the
738
`['Transfer-Encoding', 'chunked']` header line when
739
creating the request.
740
741
The `encoding` argument is optional and only applies when `chunk` is a string.
742
Defaults to `'utf8'`.
743
744
The `callback` argument is optional and will be called when this chunk of data
745
is flushed.
746
747
Returns `true` if the entire data was flushed successfully to the kernel
748
buffer. Returns `false` if all or part of the data was queued in user memory.
749
`'drain'` will be emitted when the buffer is free again.
750
751
## Class: http.Server
752
<!-- YAML
753
added: v0.1.17
754
-->
755
756
This class inherits from [`net.Server`][] and has the following additional
757
events:
758
759
### Event: 'checkContinue'
760
<!-- YAML
761
added: v0.3.0
762
-->
763
764
* `request` {http.IncomingMessage}
765
* `response` {http.ServerResponse}
766
767
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
768
If this event is not listened for, the server will automatically respond
769
with a `100 Continue` as appropriate.
770
771
Handling this event involves calling [`response.writeContinue()`][] if the
772
client should continue to send the request body, or generating an appropriate
773
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
774
the request body.
775
776
Note that when this event is emitted and handled, the [`'request'`][] event will
777
not be emitted.
778
779
### Event: 'checkExpectation'
780
<!-- YAML
781
added: v5.5.0
782
-->
783
784
* `request` {http.IncomingMessage}
785
* `response` {http.ServerResponse}
786
787
Emitted each time a request with an HTTP `Expect` header is received, where the
788
value is not `100-continue`. If this event is not listened for, the server will
789
automatically respond with a `417 Expectation Failed` as appropriate.
790
791
Note that when this event is emitted and handled, the [`'request'`][] event will
792
not be emitted.
793
794
### Event: 'clientError'
795
<!-- YAML
796
added: v0.1.94
797
changes:
798
- version: v6.0.0
799
pr-url: https://github.com/nodejs/node/pull/4557
800
description: The default action of calling `.destroy()` on the `socket`
801
will no longer take place if there are listeners attached
802
for `'clientError'`.
803
- version: v9.4.0
804
pr-url: https://github.com/nodejs/node/pull/17672
805
description: The `rawPacket` is the current buffer that just parsed. Adding
806
this buffer to the error object of `'clientError'` event is to
807
make it possible that developers can log the broken packet.
808
-->
809
810
* `exception` {Error}
811
* `socket` {net.Socket}
812
813
If a client connection emits an `'error'` event, it will be forwarded here.
814
Listener of this event is responsible for closing/destroying the underlying
815
socket. For example, one may wish to more gracefully close the socket with a
816
custom HTTP response instead of abruptly severing the connection.
817
818
Default behavior is to close the socket with an HTTP '400 Bad Request' response
819
if possible, otherwise the socket is immediately destroyed.
820
821
`socket` is the [`net.Socket`][] object that the error originated from.
822
823
```js
824
const http = require('http');
825
826
const server = http.createServer((req, res) => {
827
res.end();
828
});
829
server.on('clientError', (err, socket) => {
830
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
831
});
832
server.listen(8000);
833
```
834
835
When the `'clientError'` event occurs, there is no `request` or `response`
836
object, so any HTTP response sent, including response headers and payload,
837
*must* be written directly to the `socket` object. Care must be taken to
838
ensure the response is a properly formatted HTTP response message.
839
840
`err` is an instance of `Error` with two extra columns:
841
842
+ `bytesParsed`: the bytes count of request packet that Node.js may have parsed
843
correctly;
844
+ `rawPacket`: the raw packet of current request.
845
846
### Event: 'close'
847
<!-- YAML
848
added: v0.1.4
849
-->
850
851
Emitted when the server closes.
852
853
### Event: 'connect'
854
<!-- YAML
855
added: v0.7.0
856
-->
857
858
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
859
the [`'request'`][] event
860
* `socket` {net.Socket} Network socket between the server and client
861
* `head` {Buffer} The first packet of the tunneling stream (may be empty)
862
863
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
864
not listened for, then clients requesting a `CONNECT` method will have their
865
connections closed.
866
867
After this event is emitted, the request's socket will not have a `'data'`
868
event listener, meaning it will need to be bound in order to handle data
869
sent to the server on that socket.
870
871
### Event: 'connection'
872
<!-- YAML
873
added: v0.1.0
874
-->
875
876
* `socket` {net.Socket}
877
878
This event is emitted when a new TCP stream is established. `socket` is
879
typically an object of type [`net.Socket`][]. Usually users will not want to
880
access this event. In particular, the socket will not emit `'readable'` events
881
because of how the protocol parser attaches to the socket. The `socket` can
882
also be accessed at `request.connection`.
883
884
This event can also be explicitly emitted by users to inject connections
885
into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
886
887
### Event: 'request'
888
<!-- YAML
889
added: v0.1.0
890
-->
891
892
* `request` {http.IncomingMessage}
893
* `response` {http.ServerResponse}
894
895
Emitted each time there is a request. Note that there may be multiple requests
896
per connection (in the case of HTTP Keep-Alive connections).
897
898
### Event: 'upgrade'
899
<!-- YAML
900
added: v0.1.94
901
changes:
902
- version: v10.0.0
903
pr-url: v10.0.0
904
description: Not listening to this event no longer causes the socket
905
to be destroyed if a client sends an Upgrade header.
906
-->
907
908
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
909
the [`'request'`][] event
910
* `socket` {net.Socket} Network socket between the server and client
911
* `head` {Buffer} The first packet of the upgraded stream (may be empty)
912
913
Emitted each time a client requests an HTTP upgrade. Listening to this event
914
is optional and clients cannot insist on a protocol change.
915
916
After this event is emitted, the request's socket will not have a `'data'`
917
event listener, meaning it will need to be bound in order to handle data
918
sent to the server on that socket.
919
920
### server.close([callback])
921
<!-- YAML
922
added: v0.1.90
923
-->
924
925
* `callback` {Function}
926
927
Stops the server from accepting new connections. See [`net.Server.close()`][].
928
929
### server.listen()
930
931
Starts the HTTP server listening for connections.
932
This method is identical to [`server.listen()`][] from [`net.Server`][].
933
934
### server.listening
935
<!-- YAML
936
added: v5.7.0
937
-->
938
939
* {boolean} Indicates whether or not the server is listening for connections.
940
941
### server.maxHeadersCount
942
<!-- YAML
943
added: v0.7.0
944
-->
945
946
* {number} **Default:** `2000`
947
948
Limits maximum incoming headers count. If set to 0, no limit will be applied.
949
950
### server.setTimeout([msecs][, callback])
951
<!-- YAML
952
added: v0.9.12
953
-->
954
955
* `msecs` {number} **Default:** `120000` (2 minutes)
956
* `callback` {Function}
957
* Returns: {http.Server}
958
959
Sets the timeout value for sockets, and emits a `'timeout'` event on
960
the Server object, passing the socket as an argument, if a timeout
961
occurs.
962
963
If there is a `'timeout'` event listener on the Server object, then it
964
will be called with the timed-out socket as an argument.
965
966
By default, the Server's timeout value is 2 minutes, and sockets are
967
destroyed automatically if they time out. However, if a callback is assigned
968
to the Server's `'timeout'` event, timeouts must be handled explicitly.
969
970
### server.timeout
971
<!-- YAML
972
added: v0.9.12
973
-->
974
975
* {number} Timeout in milliseconds. **Default:** `120000` (2 minutes).
976
977
The number of milliseconds of inactivity before a socket is presumed
978
to have timed out.
979
980
A value of `0` will disable the timeout behavior on incoming connections.
981
982
The socket timeout logic is set up on connection, so changing this
983
value only affects new connections to the server, not any existing connections.
984
985
### server.keepAliveTimeout
986
<!-- YAML
987
added: v8.0.0
988
-->
989
990
* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).
991
992
The number of milliseconds of inactivity a server needs to wait for additional
993
incoming data, after it has finished writing the last response, before a socket
994
will be destroyed. If the server receives new data before the keep-alive
995
timeout has fired, it will reset the regular inactivity timeout, i.e.,
996
[`server.timeout`][].
997
998
A value of `0` will disable the keep-alive timeout behavior on incoming
999
connections.
1000
A value of `0` makes the http server behave similarly to Node.js versions prior