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