-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathhttp.md
More file actions
2040 lines (1577 loc) Β· 56.5 KB
/
http.md
File metadata and controls
2040 lines (1577 loc) Β· 56.5 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. Defaults to `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`. Defaults to `1000`.
124
* `maxSockets` {number} Maximum number of sockets to allow per
125
host. Defaults to `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
Defaults to `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: REPLACEME
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, clients receiving an upgrade header will have
475
their connections closed.
476
477
A client server pair demonstrating how to listen for the `'upgrade'` event.
478
479
```js
480
const http = require('http');
481
482
// Create an HTTP server
483
const srv = http.createServer((req, res) => {
484
res.writeHead(200, { 'Content-Type': 'text/plain' });
485
res.end('okay');
486
});
487
srv.on('upgrade', (req, socket, head) => {
488
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
489
'Upgrade: WebSocket\r\n' +
490
'Connection: Upgrade\r\n' +
491
'\r\n');
492
493
socket.pipe(socket); // echo back
494
});
495
496
// now that server is running
497
srv.listen(1337, '127.0.0.1', () => {
498
499
// make a request
500
const options = {
501
port: 1337,
502
hostname: '127.0.0.1',
503
headers: {
504
'Connection': 'Upgrade',
505
'Upgrade': 'websocket'
506
}
507
};
508
509
const req = http.request(options);
510
req.end();
511
512
req.on('upgrade', (res, socket, upgradeHead) => {
513
console.log('got upgraded!');
514
socket.end();
515
process.exit(0);
516
});
517
});
518
```
519
520
### request.abort()
521
<!-- YAML
522
added: v0.3.8
523
-->
524
525
Marks the request as aborting. Calling this will cause remaining data
526
in the response to be dropped and the socket to be destroyed.
527
528
### request.aborted
529
<!-- YAML
530
added: v0.11.14
531
-->
532
533
If a request has been aborted, this value is the time when the request was
534
aborted, in milliseconds since 1 January 1970 00:00:00 UTC.
535
536
### request.connection
537
<!-- YAML
538
added: v0.3.0
539
-->
540
541
* {net.Socket}
542
543
See [`request.socket`][]
544
545
### request.end([data[, encoding]][, callback])
546
<!-- YAML
547
added: v0.1.90
548
changes:
549
- version: REPLACEME
550
pr-url: https://github.com/nodejs/node/pull/18780
551
description: This method now returns a reference to `ClientRequest`.
552
-->
553
554
* `data` {string|Buffer}
555
* `encoding` {string}
556
* `callback` {Function}
557
* Returns: {this}
558
559
Finishes sending the request. If any parts of the body are
560
unsent, it will flush them to the stream. If the request is
561
chunked, this will send the terminating `'0\r\n\r\n'`.
562
563
If `data` is specified, it is equivalent to calling
564
[`request.write(data, encoding)`][] followed by `request.end(callback)`.
565
566
If `callback` is specified, it will be called when the request stream
567
is finished.
568
569
### request.flushHeaders()
570
<!-- YAML
571
added: v1.6.0
572
-->
573
574
Flush the request headers.
575
576
For efficiency reasons, Node.js normally buffers the request headers until
577
`request.end()` is called or the first chunk of request data is written. It
578
then tries to pack the request headers and data into a single TCP packet.
579
580
That's usually desired (it saves a TCP round-trip), but not when the first
581
data is not sent until possibly much later. `request.flushHeaders()` bypasses
582
the optimization and kickstarts the request.
583
584
### request.getHeader(name)
585
<!-- YAML
586
added: v1.6.0
587
-->
588
589
* `name` {string}
590
* Returns: {string}
591
592
Reads out a header on the request. Note that the name is case insensitive.
593
594
Example:
595
```js
596
const contentType = request.getHeader('Content-Type');
597
```
598
599
### request.removeHeader(name)
600
<!-- YAML
601
added: v1.6.0
602
-->
603
604
* `name` {string}
605
606
Removes a header that's already defined into headers object.
607
608
Example:
609
```js
610
request.removeHeader('Content-Type');
611
```
612
613
### request.setHeader(name, value)
614
<!-- YAML
615
added: v1.6.0
616
-->
617
618
* `name` {string}
619
* `value` {string}
620
621
Sets a single header value for headers object. If this header already exists in
622
the to-be-sent headers, its value will be replaced. Use an array of strings
623
here to send multiple headers with the same name.
624
625
Example:
626
```js
627
request.setHeader('Content-Type', 'application/json');
628
```
629
630
or
631
632
```js
633
request.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
634
```
635
636
### request.setNoDelay([noDelay])
637
<!-- YAML
638
added: v0.5.9
639
-->
640
641
* `noDelay` {boolean}
642
643
Once a socket is assigned to this request and is connected
644
[`socket.setNoDelay()`][] will be called.
645
646
### request.setSocketKeepAlive([enable][, initialDelay])
647
<!-- YAML
648
added: v0.5.9
649
-->
650
651
* `enable` {boolean}
652
* `initialDelay` {number}
653
654
Once a socket is assigned to this request and is connected
655
[`socket.setKeepAlive()`][] will be called.
656
657
### request.setTimeout(timeout[, callback])
658
<!-- YAML
659
added: v0.5.9
660
-->
661
662
* `timeout` {number} Milliseconds before a request times out.
663
* `callback` {Function} Optional function to be called when a timeout occurs.
664
Same as binding to the `timeout` event.
665
666
Once a socket is assigned to this request and is connected
667
[`socket.setTimeout()`][] will be called.
668
669
Returns `request`.
670
671
### request.socket
672
<!-- YAML
673
added: v0.3.0
674
-->
675
676
* {net.Socket}
677
678
Reference to the underlying socket. Usually users will not want to access
679
this property. In particular, the socket will not emit `'readable'` events
680
because of how the protocol parser attaches to the socket. After
681
`response.end()`, the property is nulled. The `socket` may also be accessed
682
via `request.connection`.
683
684
Example:
685
686
```js
687
const http = require('http');
688
const options = {
689
host: 'www.google.com',
690
};
691
const req = http.get(options);
692
req.end();
693
req.once('response', (res) => {
694
const ip = req.socket.localAddress;
695
const port = req.socket.localPort;
696
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
697
// consume response object
698
});
699
```
700
701
### request.write(chunk[, encoding][, callback])
702
<!-- YAML
703
added: v0.1.29
704
-->
705
706
* `chunk` {string|Buffer}
707
* `encoding` {string}
708
* `callback` {Function}
709
710
Sends a chunk of the body. By calling this method
711
many times, a request body can be sent to a
712
server--in that case it is suggested to use the
713
`['Transfer-Encoding', 'chunked']` header line when
714
creating the request.
715
716
The `encoding` argument is optional and only applies when `chunk` is a string.
717
Defaults to `'utf8'`.
718
719
The `callback` argument is optional and will be called when this chunk of data
720
is flushed.
721
722
Returns `true` if the entire data was flushed successfully to the kernel
723
buffer. Returns `false` if all or part of the data was queued in user memory.
724
`'drain'` will be emitted when the buffer is free again.
725
726
## Class: http.Server
727
<!-- YAML
728
added: v0.1.17
729
-->
730
731
This class inherits from [`net.Server`][] and has the following additional
732
events:
733
734
### Event: 'checkContinue'
735
<!-- YAML
736
added: v0.3.0
737
-->
738
739
* `request` {http.IncomingMessage}
740
* `response` {http.ServerResponse}
741
742
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
743
If this event is not listened for, the server will automatically respond
744
with a `100 Continue` as appropriate.
745
746
Handling this event involves calling [`response.writeContinue()`][] if the
747
client should continue to send the request body, or generating an appropriate
748
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
749
the request body.
750
751
Note that when this event is emitted and handled, the [`'request'`][] event will
752
not be emitted.
753
754
### Event: 'checkExpectation'
755
<!-- YAML
756
added: v5.5.0
757
-->
758
759
* `request` {http.IncomingMessage}
760
* `response` {http.ServerResponse}
761
762
Emitted each time a request with an HTTP `Expect` header is received, where the
763
value is not `100-continue`. If this event is not listened for, the server will
764
automatically respond with a `417 Expectation Failed` as appropriate.
765
766
Note that when this event is emitted and handled, the [`'request'`][] event will
767
not be emitted.
768
769
### Event: 'clientError'
770
<!-- YAML
771
added: v0.1.94
772
changes:
773
- version: v6.0.0
774
pr-url: https://github.com/nodejs/node/pull/4557
775
description: The default action of calling `.destroy()` on the `socket`
776
will no longer take place if there are listeners attached
777
for `clientError`.
778
- version: v9.4.0
779
pr-url: https://github.com/nodejs/node/pull/17672
780
description: The rawPacket is the current buffer that just parsed. Adding
781
this buffer to the error object of clientError event is to make
782
it possible that developers can log the broken packet.
783
-->
784
785
* `exception` {Error}
786
* `socket` {net.Socket}
787
788
If a client connection emits an `'error'` event, it will be forwarded here.
789
Listener of this event is responsible for closing/destroying the underlying
790
socket. For example, one may wish to more gracefully close the socket with a
791
custom HTTP response instead of abruptly severing the connection.
792
793
Default behavior is to close the socket with an HTTP '400 Bad Request' response
794
if possible, otherwise the socket is immediately destroyed.
795
796
`socket` is the [`net.Socket`][] object that the error originated from.
797
798
```js
799
const http = require('http');
800
801
const server = http.createServer((req, res) => {
802
res.end();
803
});
804
server.on('clientError', (err, socket) => {
805
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
806
});
807
server.listen(8000);
808
```
809
810
When the `'clientError'` event occurs, there is no `request` or `response`
811
object, so any HTTP response sent, including response headers and payload,
812
*must* be written directly to the `socket` object. Care must be taken to
813
ensure the response is a properly formatted HTTP response message.
814
815
`err` is an instance of `Error` with two extra columns:
816
817
+ `bytesParsed`: the bytes count of request packet that Node.js may have parsed
818
correctly;
819
+ `rawPacket`: the raw packet of current request.
820
821
### Event: 'close'
822
<!-- YAML
823
added: v0.1.4
824
-->
825
826
Emitted when the server closes.
827
828
### Event: 'connect'
829
<!-- YAML
830
added: v0.7.0
831
-->
832
833
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
834
the [`'request'`][] event
835
* `socket` {net.Socket} Network socket between the server and client
836
* `head` {Buffer} The first packet of the tunneling stream (may be empty)
837
838
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
839
not listened for, then clients requesting a `CONNECT` method will have their
840
connections closed.
841
842
After this event is emitted, the request's socket will not have a `'data'`
843
event listener, meaning it will need to be bound in order to handle data
844
sent to the server on that socket.
845
846
### Event: 'connection'
847
<!-- YAML
848
added: v0.1.0
849
-->
850
851
* `socket` {net.Socket}
852
853
This event is emitted when a new TCP stream is established. `socket` is
854
typically an object of type [`net.Socket`][]. Usually users will not want to
855
access this event. In particular, the socket will not emit `'readable'` events
856
because of how the protocol parser attaches to the socket. The `socket` can
857
also be accessed at `request.connection`.
858
859
This event can also be explicitly emitted by users to inject connections
860
into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
861
862
### Event: 'request'
863
<!-- YAML
864
added: v0.1.0
865
-->
866
867
* `request` {http.IncomingMessage}
868
* `response` {http.ServerResponse}
869
870
Emitted each time there is a request. Note that there may be multiple requests
871
per connection (in the case of HTTP Keep-Alive connections).
872
873
### Event: 'upgrade'
874
<!-- YAML
875
added: v0.1.94
876
-->
877
878
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
879
the [`'request'`][] event
880
* `socket` {net.Socket} Network socket between the server and client
881
* `head` {Buffer} The first packet of the upgraded stream (may be empty)
882
883
Emitted each time a client requests an HTTP upgrade. If this event is not
884
listened for, then clients requesting an upgrade will have their connections
885
closed.
886
887
After this event is emitted, the request's socket will not have a `'data'`
888
event listener, meaning it will need to be bound in order to handle data
889
sent to the server on that socket.
890
891
### server.close([callback])
892
<!-- YAML
893
added: v0.1.90
894
-->
895
896
* `callback` {Function}
897
898
Stops the server from accepting new connections. See [`net.Server.close()`][].
899
900
### server.listen()
901
902
Starts the HTTP server listening for connections.
903
This method is identical to [`server.listen()`][] from [`net.Server`][].
904
905
### server.listening
906
<!-- YAML
907
added: v5.7.0
908
-->
909
910
* {boolean}
911
912
A Boolean indicating whether or not the server is listening for
913
connections.
914
915
### server.maxHeadersCount
916
<!-- YAML
917
added: v0.7.0
918
-->
919
920
* {number} Defaults to 2000.
921
922
Limits maximum incoming headers count, equal to 2000 by default. If set to 0 -
923
no limit will be applied.
924
925
### server.setTimeout([msecs][, callback])
926
<!-- YAML
927
added: v0.9.12
928
-->
929
930
* `msecs` {number} Defaults to 120000 (2 minutes).
931
* `callback` {Function}
932
933
Sets the timeout value for sockets, and emits a `'timeout'` event on
934
the Server object, passing the socket as an argument, if a timeout
935
occurs.
936
937
If there is a `'timeout'` event listener on the Server object, then it
938
will be called with the timed-out socket as an argument.
939
940
By default, the Server's timeout value is 2 minutes, and sockets are
941
destroyed automatically if they time out. However, if a callback is assigned
942
to the Server's `'timeout'` event, timeouts must be handled explicitly.
943
944
Returns `server`.
945
946
### server.timeout
947
<!-- YAML
948
added: v0.9.12
949
-->
950
951
* {number} Timeout in milliseconds. Defaults to 120000 (2 minutes).
952
953
The number of milliseconds of inactivity before a socket is presumed
954
to have timed out.
955
956
A value of `0` will disable the timeout behavior on incoming connections.
957
958
The socket timeout logic is set up on connection, so changing this
959
value only affects new connections to the server, not any existing connections.
960
961
### server.keepAliveTimeout
962
<!-- YAML
963
added: v8.0.0
964
-->
965
966
* {number} Timeout in milliseconds. Defaults to 5000 (5 seconds).
967
968
The number of milliseconds of inactivity a server needs to wait for additional
969
incoming data, after it has finished writing the last response, before a socket
970
will be destroyed. If the server receives new data before the keep-alive
971
timeout has fired, it will reset the regular inactivity timeout, i.e.,
972
[`server.timeout`][].
973
974
A value of `0` will disable the keep-alive timeout behavior on incoming
975
connections.
976
A value of `0` makes the http server behave similarly to Node.js versions prior
977
to 8.0.0, which did not have a keep-alive timeout.
978
979
The socket timeout logic is set up on connection, so changing this value only
980
affects new connections to the server, not any existing connections.
981
982
## Class: http.ServerResponse
983
<!-- YAML
984
added: v0.1.17
985
-->
986
987
This object is created internally by an HTTP server--not by the user. It is
988
passed as the second parameter to the [`'request'`][] event.
989
990
The response implements, but does not inherit from, the [Writable Stream][]
991
interface. This is an [`EventEmitter`][] with the following events:
992
993
### Event: 'close'
994
<!-- YAML
995
added: v0.6.7
996
-->
997
998
Indicates that the underlying connection was terminated before
999
[`response.end()`][] was called or able to flush.
1000