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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
|
# HTTP
<!--introduced_in=v0.10.0-->
> Stability: 2 - Stable
<!-- source_link=lib/http.js -->
To use the HTTP server and client one must `require('http')`.
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:
<!-- eslint-skip -->
```js
{ '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 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.
The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
of these values set to their respective defaults.
To configure any of them, a custom [`http.Agent`][] instance must be created.
```js
const http = require('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
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.
Node.js does not check whether Content-Length and the length of the
body which has been transmitted are equal or not.
### 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:
```js
const http = require('http');
const net = require('net');
const { URL } = require('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.
```js
const http = require('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.
```js
const http = require('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.end([data[, encoding]][, callback])`
<!-- YAML
added: v0.1.90
changes:
- 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}
* `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.getRawHeaderNames()`
<!-- YAML
added:
- v15.13.0
- v14.17.0
-->
* Returns: {string\[]}
Returns an array containing the unique names of the current outgoing raw
headers. Header names are returned with their exact casing being set.
```js
request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = request.getRawHeaderNames();
// headerNames === ['Foo', 'Set-Cookie']
```
### `request.maxHeadersCount`
* {number} **Default:** `2000`
Limits maximum response headers count. If set to 0, no limit will be applied.
### `request.path`
<!-- YAML
added: v0.4.0
-->
* {string} The request path.
### `request.method`
<!-- YAML
added: v0.1.97
-->
* {string} The request method.
### `request.host`
<!-- YAML
added:
- v14.5.0
- v12.19.0
-->
* {string} The request host.
### `request.protocol`
<!-- YAML
added:
- v14.5.0
- v12.19.0
-->
* {string} The request protocol.
### `request.removeHeader(name)`
<!-- YAML
added: v1.6.0
-->
* `name` {string}
Removes a header that's already defined into headers object.
```js
request.removeHeader('Content-Type');
```
### `request.reusedSocket`
<!-- YAML
added:
- v13.0.0
- v12.16.0
-->
* {boolean} Whether the request is send through a reused socket.
When sending request through a keep-alive enabled agent, the underlying socket
might be reused. But if server closes connection at unfortunate time, client
may run into a 'ECONNRESET' error.
```js
const http = require('http');
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
```
By marking a request whether it reused socket or not, we can do
automatic error retry base on it.
```js
const http = require('http');
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
```
### `request.setHeader(name, value)`
<!-- YAML
added: v1.6.0
-->
* `name` {string}
* `value` {any}
Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, [`request.getHeader()`][] may return
non-string values. However, the non-string values will be converted to strings
for network transmission.
```js
request.setHeader('Content-Type', 'application/json');
```
or
```js
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
```
When the value is a string an exception will be thrown if it contains
characters outside the `latin1` encoding.
If you need to pass UTF-8 characters in the value please encode the value
using the [RFC 8187][] standard.
```js
const filename = 'Rock 🎵.txt';
request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`);
```
### `request.setNoDelay([noDelay])`
<!-- YAML
added: v0.5.9
-->
* `noDelay` {boolean}
Once a socket is assigned to this request and is connected
[`socket.setNoDelay()`][] will be called.
### `request.setSocketKeepAlive([enable][, initialDelay])`
<!-- YAML
added: v0.5.9
-->
* `enable` {boolean}
* `initialDelay` {number}
Once a socket is assigned to this request and is connected
[`socket.setKeepAlive()`][] will be called.
### `request.setTimeout(timeout[, callback])`
<!-- YAML
added: v0.5.9
changes:
- version: v9.0.0
pr-url: https://github.com/nodejs/node/pull/8895
description: Consistently set socket timeout only when the socket connects.
-->
* `timeout` {number} Milliseconds before a request times out.
* `callback` {Function} Optional function to be called when a timeout occurs.
Same as binding to the `'timeout'` event.
* Returns: {http.ClientRequest}
Once a socket is assigned to this request and is connected
[`socket.setTimeout()`][] will be called.
### `request.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket.
```js
const http = require('http');
const options = {
host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// Consume response object
});
```
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket}.
### `request.writableEnded`
<!-- YAML
added: v12.9.0
-->
* {boolean}
Is `true` after [`request.end()`][] has been called. This property
does not indicate whether the data has been flushed, for this use
[`request.writableFinished`][] instead.
### `request.writableFinished`
<!-- YAML
added: v12.7.0
-->
* {boolean}
Is `true` if all data has been flushed to the underlying system, immediately
before the [`'finish'`][] event is emitted.
### `request.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.29
-->
* `chunk` {string|Buffer}
* `encoding` {string}
* `callback` {Function}
* Returns: {boolean}
Sends a chunk of the body. This method can be called multiple times. If no
`Content-Length` is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
`Transfer-Encoding: chunked` header is added. Calling [`request.end()`][]
is necessary to finish sending the request.
The `encoding` argument is optional and only applies when `chunk` is a string.
Defaults to `'utf8'`.
The `callback` argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is free again.
When `write` function is called with empty string or buffer, it does
nothing and waits for more input.
## Class: `http.Server`
<!-- YAML
added: v0.1.17
-->
* Extends: {net.Server}
### Event: `'checkContinue'`
<!-- YAML
added: v0.3.0
-->
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
If this event is not listened for, the server will automatically respond
with a `100 Continue` as appropriate.
Handling this event involves calling [`response.writeContinue()`][] if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.
When this event is emitted and handled, the [`'request'`][] event will
not be emitted.
### Event: `'checkExpectation'`
<!-- YAML
added: v5.5.0
-->
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
Emitted each time a request with an HTTP `Expect` header is received, where the
value is not `100-continue`. If this event is not listened for, the server will
automatically respond with a `417 Expectation Failed` as appropriate.
When this event is emitted and handled, the [`'request'`][] event will
not be emitted.
### Event: `'clientError'`
<!-- YAML
added: v0.1.94
changes:
- version: v12.0.0
pr-url: https://github.com/nodejs/node/pull/25605
description: The default behavior will return a 431 Request Header
Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.
- version: v9.4.0
pr-url: https://github.com/nodejs/node/pull/17672
description: The `rawPacket` is the current buffer that just parsed. Adding
this buffer to the error object of `'clientError'` event is to
make it possible that developers can log the broken packet.
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/4557
description: The default action of calling `.destroy()` on the `socket`
will no longer take place if there are listeners attached
for `'clientError'`.
-->
* `exception` {Error}
* `socket` {stream.Duplex}
If a client connection emits an `'error'` event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection.
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}.
Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable or has already
written data it is immediately destroyed.
`socket` is the [`net.Socket`][] object that the error originated from.
```js
const http = require('http');
const server = http.createServer((req, res) => {
res.end();
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
```
When the `'clientError'` event occurs, there is no `request` or `response`
object, so any HTTP response sent, including response headers and payload,
_must_ be written directly to the `socket` object. Care must be taken to
ensure the response is a properly formatted HTTP response message.
`err` is an instance of `Error` with two extra columns:
* `bytesParsed`: the bytes count of request packet that Node.js may have parsed
correctly;
* `rawPacket`: the raw packet of current request.
In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of `ECONNRESET` errors. Before
trying to send data to the socket, it is better to check that it is still
writable.
```js
server.on('clientError', (err, socket) => {
if (err.code === 'ECONNRESET' || !socket.writable) {
return;
}
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
```
### Event: `'close'`
<!-- YAML
added: v0.1.4
-->
Emitted when the server closes.
### Event: `'connect'`
<!-- YAML
added: v0.7.0
-->
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
the [`'request'`][] event
* `socket` {stream.Duplex} Network socket between the server and client
* `head` {Buffer} The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
not listened for, then clients requesting 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}.
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
### Event: `'connection'`
<!-- YAML
added: v0.1.0
-->
* `socket` {stream.Duplex}
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
access this event. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket. The `socket` can
also be accessed at `request.socket`.
This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
If `socket.setTimeout()` is called here, the timeout will be replaced with
`server.keepAliveTimeout` when the socket has served a request (if
`server.keepAliveTimeout` is non-zero).
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: `'request'`
<!-- YAML
added: v0.1.0
-->
* `request` {http.IncomingMessage}
* `response` {http.ServerResponse}
Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).
### Event: `'upgrade'`
<!-- YAML
added: v0.1.94
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/19981
description: Not listening to this event no longer causes the socket
to be destroyed if a client sends an Upgrade header.
-->
* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
the [`'request'`][] event
* `socket` {stream.Duplex} Network socket between the server and client
* `head` {Buffer} The first packet of the upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
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}.
### `server.close([callback])`
<!-- YAML
added: v0.1.90
-->
* `callback` {Function}
Stops the server from accepting new connections. See [`net.Server.close()`][].
### `server.headersTimeout`
<!-- YAML
added:
- v11.3.0
- v10.14.0
-->
* {number} **Default:** `60000`
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.
### `server.listen()`
Starts the HTTP server listening for connections.
This method is identical to [`server.listen()`][] from [`net.Server`][].
### `server.listening`
<!-- YAML
added: v5.7.0
-->
* {boolean} Indicates whether or not the server is listening for connections.
### `server.maxHeadersCount`
<!-- YAML
added: v0.7.0
-->
* {number} **Default:** `2000`
Limits maximum incoming headers count. If set to 0, no limit will be applied.
### `server.requestTimeout`
<!-- YAML
added: v14.11.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/41263
description: The default request timeout changed
from no timeout to 300s (5 minutes).
-->
* {number} **Default:** `300000`
Sets the timeout value in milliseconds for receiving the entire request from
the client.
If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.
### `server.setTimeout([msecs][, callback])`
<!-- YAML
added: v0.9.12
changes:
- version: v13.0.0
pr-url: https://github.com/nodejs/node/pull/27558
description: The default timeout changed from 120s to 0 (no timeout).
-->
* `msecs` {number} **Default:** 0 (no timeout)
* `callback` {Function}
* Returns: {http.Server}
Sets the timeout value for sockets, and emits a `'timeout'` event on
the Server object, passing the socket as an argument, if a timeout
occurs.
If there is a `'timeout'` event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's `'timeout'` event, timeouts must be handled
explicitly.
### `server.maxRequestsPerSocket`
<!-- YAML
added: v16.10.0
-->
* {number} Requests per socket. **Default:** 0 (no limit)
The maximum number of requests socket can handle
before closing keep alive connection.
A value of `0` will disable the limit.
When the limit is reached it will set the `Connection` header value to `close`,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get `503 Service Unavailable` as a response.
### `server.timeout`
<!-- YAML
added: v0.9.12
changes:
- version: v13.0.0
pr-url: https://github.com/nodejs/node/pull/27558
description: The default timeout changed from 120s to 0 (no timeout).
-->
* {number} Timeout in milliseconds. **Default:** 0 (no timeout)
The number of milliseconds of inactivity before a socket is presumed
to have timed out.
A value of `0` will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.
### `server.keepAliveTimeout`
<!-- YAML
added: v8.0.0
-->
* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).
The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e.,
[`server.timeout`][].
A value of `0` will disable the keep-alive timeout behavior on incoming
connections.
A value of `0` makes the http server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.
## Class: `http.ServerResponse`
<!-- YAML
added: v0.1.17
-->
* Extends: {http.OutgoingMessage}
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the [`'request'`][] event.
### Event: `'close'`
<!-- YAML
added: v0.6.7
-->
Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).
### Event: `'finish'`
<!-- YAML
added: v0.3.6
-->
Emitted when the response 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 client has received anything yet.
### `response.addTrailers(headers)`
<!-- YAML
added: v0.3.0
-->
* `headers` {Object}
This method adds HTTP trailing headers (a header but at the end of the
message) to the response.
Trailers will **only** be emitted if chunked encoding is used for the
response; if it is not (e.g. if the request was HTTP/1.0), they will
be silently discarded.
HTTP requires the `Trailer` header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,
```js
response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();
```
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
### `response.connection`
<!-- YAML
added: v0.3.0
deprecated: v13.0.0
-->
> Stability: 0 - Deprecated. Use [`response.socket`][].
* {stream.Duplex}
See [`response.socket`][].
### `response.cork()`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
See [`writable.cork()`][].
### `response.end([data[, encoding]][, callback])`
<!-- YAML
added: v0.1.90
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18780
description: This method now returns a reference to `ServerResponse`.
-->
* `data` {string|Buffer}
* `encoding` {string}
* `callback` {Function}
* Returns: {this}
This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, `response.end()`, MUST be called on each response.
If `data` is specified, it is similar in effect to calling
[`response.write(data, encoding)`][] followed by `response.end(callback)`.
If `callback` is specified, it will be called when the response stream
is finished.
### `response.finished`
<!-- YAML
added: v0.0.2
deprecated:
- v13.4.0
- v12.16.0
-->
> Stability: 0 - Deprecated. Use [`response.writableEnded`][].
* {boolean}
The `response.finished` property will be `true` if [`response.end()`][]
has been called.
### `response.flushHeaders()`
<!-- YAML
added: v1.6.0
-->
Flushes the response headers. See also: [`request.flushHeaders()`][].
### `response.getHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string}
* Returns: {any}
Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to [`response.setHeader()`][].
```js
response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
```
### `response.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
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
```
### `response.getHeaders()`
<!-- YAML
added: v7.7.0
-->
* Returns: {Object}
Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.
The object returned by the `response.getHeaders()` method _does not_
prototypically inherit from the JavaScript `Object`. This means that typical
`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others
are not defined and _will not work_.
```js
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
```
### `response.hasHeader(name)`
<!-- YAML
added: v7.7.0
-->
* `name` {string}
* Returns: {boolean}
Returns `true` if the header identified by `name` is currently set in the
outgoing headers. The header name matching is case-insensitive.
```js
const hasContentType = response.hasHeader('content-type');
```
### `response.headersSent`
<!-- YAML
added: v0.9.3
-->
* {boolean}
Boolean (read-only). True if headers were sent, false otherwise.
### `response.removeHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string}
Removes a header that's queued for implicit sending.
```js
response.removeHeader('Content-Encoding');
```
### `response.req`
<!-- YAML
added: v15.7.0
-->
* {http.IncomingMessage}
A reference to the original HTTP `request` object.
### `response.sendDate`
<!-- YAML
added: v0.7.5
-->
* {boolean}
When true, the Date header will be automatically generated and sent in
the response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date header
in responses.
### `response.setHeader(name, value)`
<!-- YAML
added: v0.4.0
-->
* `name` {string}
* `value` {any}
* Returns: {http.ServerResponse}
Returns the response object.
Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, [`response.getHeader()`][] may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.
```js
response.setHeader('Content-Type', 'text/html');
```
or
```js
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
```
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
When headers have been set with [`response.setHeader()`][], they will be merged
with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence.
```js
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
```
If [`response.writeHead()`][] method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the [`response.getHeader()`][] on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
[`response.setHeader()`][] instead of [`response.writeHead()`][].
### `response.setTimeout(msecs[, callback])`
<!-- YAML
added: v0.9.12
-->
* `msecs` {number}
* `callback` {Function}
* Returns: {http.ServerResponse}
Sets the Socket's timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
the response object.
If no `'timeout'` listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's `'timeout'` events,
timed out sockets must be handled explicitly.
### `response.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
because of how the protocol parser attaches to the socket. After
`response.end()`, the property is nulled.
```js
const http = require('http');
const server = http.createServer((req, res) => {
const ip = res.socket.remoteAddress;
const port = res.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
```
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket}.
### `response.statusCode`
<!-- YAML
added: v0.4.0
-->
* {number} **Default:** `200`
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.
```js
response.statusCode = 404;
```
After response header was sent to the client, this property indicates the
status code which was sent out.
### `response.statusMessage`
<!-- YAML
added: v0.11.8
-->
* {string}
When using implicit headers (not calling [`response.writeHead()`][] explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as `undefined` then the standard
message for the status code will be used.
```js
response.statusMessage = 'Not found';
```
After response header was sent to the client, this property indicates the
status message which was sent out.
### `response.uncork()`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
See [`writable.uncork()`][].
### `response.writableEnded`
<!-- YAML
added: v12.9.0
-->
* {boolean}
Is `true` after [`response.end()`][] has been called. This property
does not indicate whether the data has been flushed, for this use
[`response.writableFinished`][] instead.
### `response.writableFinished`
<!-- YAML
added: v12.7.0
-->
* {boolean}
Is `true` if all data has been flushed to the underlying system, immediately
before the [`'finish'`][] event is emitted.
### `response.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.29
-->
* `chunk` {string|Buffer}
* `encoding` {string} **Default:** `'utf8'`
* `callback` {Function}
* Returns: {boolean}
If this method is called and [`response.writeHead()`][] has not been called,
it will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.
In the `http` module, the response body is omitted when the
request is a HEAD request. Similarly, the `204` and `304` responses
_must not_ include a message body.
`chunk` can be a string or a buffer. If `chunk` is a string,
the second parameter specifies how to encode it into a byte stream.
`callback` will be called when this chunk of data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part
body encodings that may be used.
The first time [`response.write()`][] is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time [`response.write()`][] is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is free again.
### `response.writeContinue()`
<!-- YAML
added: v0.3.0
-->
Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the [`'checkContinue'`][] event on
`Server`.
### `response.writeHead(statusCode[, statusMessage][, headers])`
<!-- YAML
added: v0.1.30
changes:
- version: v14.14.0
pr-url: https://github.com/nodejs/node/pull/35274
description: Allow passing headers as an array.
- version:
- v11.10.0
- v10.17.0
pr-url: https://github.com/nodejs/node/pull/25974
description: Return `this` from `writeHead()` to allow chaining with
`end()`.
- version:
- v5.11.0
- v4.4.5
pr-url: https://github.com/nodejs/node/pull/6291
description: A `RangeError` is thrown if `statusCode` is not a number in
the range `[100, 999]`.
-->
* `statusCode` {number}
* `statusMessage` {string}
* `headers` {Object|Array}
* Returns: {http.ServerResponse}
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
Optionally one can give a human-readable `statusMessage` as the second
argument.
`headers` may be an `Array` where the keys and values are in the same list.
It is _not_ a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values. The array is in the same
format as `request.rawHeaders`.
Returns a reference to the `ServerResponse`, so that calls can be chained.
```js
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
```
This method must only be called once on a message and it must
be called before [`response.end()`][] is called.
If [`response.write()`][] or [`response.end()`][] are called before calling
this, the implicit/mutable headers will be calculated and call this function.
When headers have been set with [`response.setHeader()`][], they will be merged
with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence.
If this method is called and [`response.setHeader()`][] has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the [`response.getHeader()`][] on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
[`response.setHeader()`][] instead.
```js
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
```
`Content-Length` is given in bytes, not characters. Use
[`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js
does not check whether `Content-Length` and the length of the body which has
been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters
will result in a [`TypeError`][] being thrown.
### `response.writeProcessing()`
<!-- YAML
added: v10.0.0
-->
Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.
## Class: `http.IncomingMessage`
<!-- YAML
added: v0.1.17
changes:
- version: v15.5.0
pr-url: https://github.com/nodejs/node/pull/33035
description: The `destroyed` value returns `true` after the incoming data
is consumed.
- version:
- v13.1.0
- v12.16.0
pr-url: https://github.com/nodejs/node/pull/30135
description: The `readableHighWaterMark` value mirrors that of the socket.
-->
* Extends: {stream.Readable}
An `IncomingMessage` object is created by [`http.Server`][] or
[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][]
and [`'response'`][] event respectively. It may be used to access response
status, headers and data.
Different from its `socket` value which is a subclass of {stream.Duplex}, the
`IncomingMessage` itself extends {stream.Readable} and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
### Event: `'aborted'`
<!-- YAML
added: v0.3.8
deprecated:
- v17.0.0
- v16.12.0
-->
> Stability: 0 - Deprecated. Listen for `'close'` event instead.
Emitted when the request has been aborted.
### Event: `'close'`
<!-- YAML
added: v0.4.2
changes:
- version: v16.0.0
pr-url: https://github.com/nodejs/node/pull/33035
description: The close event is now emitted when the request has been completed and not when the
underlying socket is closed.
-->
Emitted when the request has been completed.
### `message.aborted`
<!-- YAML
added: v10.1.0
deprecated:
- v17.0.0
- v16.12.0
-->
> Stability: 0 - Deprecated. Check `message.destroyed` from {stream.Readable}.
* {boolean}
The `message.aborted` property will be `true` if the request has
been aborted.
### `message.complete`
<!-- YAML
added: v0.3.0
-->
* {boolean}
The `message.complete` property will be `true` if a complete HTTP message has
been received and successfully parsed.
This property is particularly useful as a means of determining if a client or
server fully transmitted a message before a connection was terminated:
```js
const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST'
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
```
### `message.connection`
<!-- YAML
added: v0.1.90
deprecated: v16.0.0
-->
> Stability: 0 - Deprecated. Use [`message.socket`][].
Alias for [`message.socket`][].
### `message.destroy([error])`
<!-- YAML
added: v0.3.0
changes:
- version:
- v14.5.0
- v12.19.0
pr-url: https://github.com/nodejs/node/pull/32789
description: The function returns `this` for consistency with other Readable
streams.
-->
* `error` {Error}
* Returns: {this}
Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`
is provided, an `'error'` event is emitted on the socket and `error` is passed
as an argument to any listeners on the event.
### `message.headers`
<!-- YAML
added: v0.1.5
changes:
- version: v15.1.0
pr-url: https://github.com/nodejs/node/pull/35281
description: >-
`message.headers` is now lazily computed using an accessor property
on the prototype and is no longer enumerable.
-->
* {Object}
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
```js
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.getHeaders());
```
Duplicates in raw headers are handled in the following ways, depending on the
header name:
* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
`retry-after`, `server`, or `user-agent` are discarded.
* `set-cookie` is always an array. Duplicates are added to the array.
* For duplicate `cookie` headers, the values are joined together with '; '.
* For all other headers, the values are joined together with ', '.
### `message.httpVersion`
<!-- YAML
added: v0.1.1
-->
* {string}
In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either `'1.1'` or `'1.0'`.
Also `message.httpVersionMajor` is the first integer and
`message.httpVersionMinor` is the second.
### `message.method`
<!-- YAML
added: v0.1.1
-->
* {string}
**Only valid for request obtained from [`http.Server`][].**
The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
### `message.rawHeaders`
<!-- YAML
added: v0.11.6
-->
* {string\[]}
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is _not_ a
list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
```js
// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*/*' ]
console.log(request.rawHeaders);
```
### `message.rawTrailers`
<!-- YAML
added: v0.11.6
-->
* {string\[]}
The raw request/response trailer keys and values exactly as they were
received. Only populated at the `'end'` event.
### `message.setTimeout(msecs[, callback])`
<!-- YAML
added: v0.5.9
-->
* `msecs` {number}
* `callback` {Function}
* Returns: {http.IncomingMessage}
Calls `message.socket.setTimeout(msecs, callback)`.
### `message.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
The [`net.Socket`][] object associated with the connection.
With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
client's authentication details.
This property is guaranteed to be an instance of the {net.Socket} class,
a subclass of {stream.Duplex}, unless the user specified a socket
type other than {net.Socket} or internally nulled.
### `message.statusCode`
<!-- YAML
added: v0.1.1
-->
* {number}
**Only valid for response obtained from [`http.ClientRequest`][].**
The 3-digit HTTP response status code. E.G. `404`.
### `message.statusMessage`
<!-- YAML
added: v0.11.10
-->
* {string}
**Only valid for response obtained from [`http.ClientRequest`][].**
The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server
Error`.
### `message.trailers`
<!-- YAML
added: v0.3.0
-->
* {Object}
The request/response trailers object. Only populated at the `'end'` event.
### `message.url`
<!-- YAML
added: v0.1.90
-->
* {string}
**Only valid for request obtained from [`http.Server`][].**
Request URL string. This contains only the URL that is present in the actual
HTTP request. Take the following request:
```http
GET /status?name=ryan HTTP/1.1
Accept: text/plain
```
To parse the URL into its parts:
```js
new URL(request.url, `http://${request.getHeaders().host}`);
```
When `request.url` is `'/status?name=ryan'` and
`request.getHeaders().host` is `'localhost:3000'`:
```console
$ node
> new URL(request.url, `http://${request.getHeaders().host}`)
URL {
href: 'http://localhost:3000/status?name=ryan',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
```
## Class: `http.OutgoingMessage`
<!-- YAML
added: v0.1.17
-->
* Extends: {Stream}
This class serves as the parent class of [`http.ClientRequest`][]
and [`http.ServerResponse`][]. It is an abstract of outgoing message from
the perspective of the participants of HTTP transaction.
### Event: `'drain'`
<!-- YAML
added: v0.3.6
-->
Emitted when the buffer of the message is free again.
### Event: `'finish'`
<!-- YAML
added: v0.1.17
-->
Emitted when the transmission is finished successfully.
### Event: `'prefinish'`
<!-- YAML
added: v0.11.6
-->
Emitted when `outgoingMessage.end` was called.
When the event is emitted, all data has been processed but not necessarily
completely flushed.
### `outgoingMessage.addTrailers(headers)`
<!-- YAML
added: v0.3.0
-->
* `headers` {Object}
Adds HTTP trailers (headers but at the end of the message) to the message.
Trailers are **only** be emitted if the message is chunked encoded. If not,
the trailer will be silently discarded.
HTTP requires the `Trailer` header to be sent to emit trailers,
with a list of header fields in its value, e.g.
```js
message.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
message.write(fileData);
message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
message.end();
```
Attempting to set a header field name or value that contains invalid characters
will result in a `TypeError` being thrown.
### `outgoingMessage.connection`
<!-- YAML
added: v0.3.0
deprecated:
- v15.12.0
- v14.17.1
-->
> Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead.
Aliases of `outgoingMessage.socket`
### `outgoingMessage.cork()`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
See [`writable.cork()`][].
### `outgoingMessage.destroy([error])`
<!-- YAML
added: v0.3.0
-->
* `error` {Error} Optional, an error to emit with `error` event
* Returns: {this}
Destroys the message. Once a socket is associated with the message
and is connected, that socket will be destroyed as well.
### `outgoingMessage.end(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.90
changes:
- version: v0.11.6
description: add `callback` argument.
-->
* `chunk` {string | Buffer}
* `encoding` {string} Optional, **Default**: `utf8`
* `callback` {Function} Optional
* Returns: {this}
Finishes the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will
send the terminating chunk `0\r\n\r\n`, and send the trailer (if any).
If `chunk` is specified, it is equivalent to call
`outgoingMessage.write(chunk, encoding)`, followed by
`outgoingMessage.end(callback)`.
If `callback` is provided, it will be called when the message is finished.
(equivalent to the callback to event `finish`)
### `outgoingMessage.flushHeaders()`
<!-- YAML
added: v1.6.0
-->
Compulsorily flushes the message headers
For efficiency reason, Node.js normally buffers the message headers
until `outgoingMessage.end()` is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.
It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. `outgoingMessage.flushHeaders()`
bypasses the optimization and kickstarts the request.
### `outgoingMessage.getHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string} Name of header
* Returns {string | undefined}
Gets the value of HTTP header with the given name. If such a name doesn't
exist in message, it will be `undefined`.
### `outgoingMessage.getHeaderNames()`
<!-- YAML
added: v7.7.0
-->
* Returns {string\[]}
Returns an array of names of headers of the outgoing outgoingMessage. All
names are lowercase.
### `outgoingMessage.getHeaders()`
<!-- YAML
added: v7.7.0
-->
* Returns: {Object}
Returns a shallow copy of the current outgoing headers. Since a shallow
copy is used, array values may be mutated without additional calls to
various header-related HTTP module methods. The keys of the returned
object are the header names and the values are the respective header
values. All header names are lowercase.
The object returned by the `outgoingMessage.getHeaders()` method does
not prototypically inherit from the JavaScript Object. This means that
typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`,
and others are not defined and will not work.
```js
outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
```
### `outgoingMessage.hasHeader(name)`
<!-- YAML
added: v7.7.0
-->
* `name` {string}
* Returns {boolean}
Returns `true` if the header identified by `name` is currently set in the
outgoing headers. The header name is case-insensitive.
```js
const hasContentType = outgoingMessage.hasHeader('content-type');
```
### `outgoingMessage.headersSent`
<!-- YAML
added: v0.9.3
-->
* {boolean}
Read-only. `true` if the headers were sent, otherwise `false`.
### `outgoingMessage.pipe()`
<!-- YAML
added: v9.0.0
-->
Overrides the pipe method of legacy `Stream` which is the parent class of
`http.outgoingMessage`.
Since `OutgoingMessage` should be a write-only stream,
call this function will throw an `Error`. Thus, it disabled the pipe method
it inherits from `Stream`.
The User should not call this function directly.
### `outgoingMessage.removeHeader(name)`
<!-- YAML
added: v0.4.0
-->
* `name` {string} Header name
Removes a header that is queued for implicit sending.
```js
outgoingMessage.removeHeader('Content-Encoding');
```
### `outgoingMessage.setHeader(name, value)`
<!-- YAML
added: v0.4.0
-->
* `name` {string} Header name
* `value` {string} Header value
* Returns: {this}
Sets a single header value for the header object.
### `outgoingMessage.setTimeout(msesc[, callback])`
<!-- YAML
added: v0.9.12
-->
* `msesc` {number}
* `callback` {Function} Optional function to be called when a timeout
occurs. Same as binding to the `timeout` event.
* Returns: {this}
Once a socket is associated with the message and is connected,
[`socket.setTimeout()`][] will be called with `msecs` as the first parameter.
### `outgoingMessage.socket`
<!-- YAML
added: v0.3.0
-->
* {stream.Duplex}
Reference to the underlying socket. Usually, users will not want to access
this property.
After calling `outgoingMessage.end()`, this property will be nulled.
### `outgoingMessage.uncork()`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
See [`writable.uncork()`][]
### `outgoingMessage.writableCorked`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
* {number}
This `outgoingMessage.writableCorked` will return the time how many
`outgoingMessage.cork()` have been called.
### `outgoingMessage.writableEnded`
<!-- YAML
added: v12.9.0
-->
* {boolean}
Readonly, `true` if `outgoingMessage.end()` has been called. Noted that
this property does not reflect whether the data has been flush. For that
purpose, use `message.writableFinished` instead.
### `outgoingMessage.writableFinished`
<!-- YAML
added: v12.7.0
-->
* {boolean}
Readonly. `true` if all data has been flushed to the underlying system.
### `outgoingMessage.writableHighWaterMark`
<!-- YAML
added: v12.9.0
-->
* {number}
This `outgoingMessage.writableHighWaterMark` will be the `highWaterMark` of
underlying socket if socket exists. Else, it would be the default
`highWaterMark`.
`highWaterMark` is the maximum amount of data that can be potentially
buffered by the socket.
### `outgoingMessage.writableLength`
<!-- YAML
added: v12.9.0
-->
* {number}
Readonly, This `outgoingMessage.writableLength` contains the number of
bytes (or objects) in the buffer ready to send.
### `outgoingMessage.writableObjectMode`
<!-- YAML
added: v12.9.0
-->
* {boolean}
Readonly, always returns `false`.
### `outgoingMessage.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.1.29
changes:
- version: v0.11.6
description: add `callback` argument.
-->
* `chunk` {string | Buffer}
* `encoding` {string} **Default**: `utf8`
* `callback` {Function}
* Returns {boolean}
If this method is called and the header is not sent, it will call
`this._implicitHeader` to flush implicit header.
If the message should not have a body (indicated by `this._hasBody`),
the call is ignored and `chunk` will not be sent. It could be useful
when handling a particular message which must not include a body.
e.g. response to `HEAD` request, `204` and `304` response.
`chunk` can be a string or a buffer. When `chunk` is a string, the
`encoding` parameter specifies how to encode `chunk` into a byte stream.
`callback` will be called when the `chunk` is flushed.
If the message is transferred in chucked encoding
(indicated by `this.chunkedEncoding`), `chunk` will be flushed as
one chunk among a stream of chunks. Otherwise, it will be flushed as the
body of message.
This method handles the raw body of the HTTP message and has nothing to do
with higher-level multi-part body encodings that may be used.
If it is the first call to this method of a message, it will send the
buffered header first, then flush the `chunk` as described above.
The second and successive calls to this method will assume the data
will be streamed and send the new data separately. It means that the response
is buffered up to the first chunk of the body.
Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in the user
memory. Event `drain` will be emitted when the buffer is free again.
## `http.METHODS`
<!-- YAML
added: v0.11.8
-->
* {string\[]}
A list of the HTTP methods that are supported by the parser.
## `http.STATUS_CODES`
<!-- YAML
added: v0.1.22
-->
* {Object}
A collection of all the standard HTTP response status codes, and the
short description of each. For example, `http.STATUS_CODES[404] === 'Not
Found'`.
## `http.createServer([options][, requestListener])`
<!-- YAML
added: v0.1.13
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/41263
description: The `requestTimeout`, `headersTimeout`, `keepAliveTimeout` and
`connectionsCheckingInterval` are supported now.
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/42163
description: The `noDelay` option now defaults to `true`.
- version: v17.7.0
pr-url: https://github.com/nodejs/node/pull/41310
description: The `noDelay`, `keepAlive` and `keepAliveInitialDelay`
options are supported now.
- version:
- v13.8.0
- v12.15.0
- v10.19.0
pr-url: https://github.com/nodejs/node/pull/31448
description: The `insecureHTTPParser` option is supported now.
- version: v13.3.0
pr-url: https://github.com/nodejs/node/pull/30570
description: The `maxHeaderSize` option is supported now.
- version:
- v9.6.0
- v8.12.0
pr-url: https://github.com/nodejs/node/pull/15752
description: The `options` argument is supported now.
-->
* `options` {Object}
* `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage`
class to be used. Useful for extending the original `IncomingMessage`.
**Default:** `IncomingMessage`.
* `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class
to be used. Useful for extending the original `ServerResponse`. **Default:**
`ServerResponse`.
* `requestTimeout`: Sets the timeout value in milliseconds for receiving
the entire request from the client.
See [`server.requestTimeout`][] for more information.
**Default:** `300000`.
* `headersTimeout`: Sets the timeout value in milliseconds for receiving
the complete HTTP headers from the client.
See [`server.headersTimeout`][] for more information.
**Default:** `60000`.
* `keepAliveTimeout`: The number of milliseconds of inactivity a server
needs to wait for additional incoming data, after it has finished writing
the last response, before a socket will be destroyed.
See [`server.keepAliveTimeout`][] for more information.
**Default:** `5000`.
* `connectionsCheckingInterval`: Sets the interval value in milliseconds to
check for request and headers timeout in incomplete requests.
**Default:** `30000`.
* `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
invalid HTTP headers when `true`. Using the insecure parser should be
avoided. See [`--insecure-http-parser`][] for more information.
**Default:** `false`
* `maxHeaderSize` {number} Optionally overrides the value of
[`--max-http-header-size`][] for requests received by this server, i.e.
the maximum length of request headers in bytes.
**Default:** 16384 (16 KB).
* `noDelay` {boolean} If set to `true`, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
**Default:** `true`.
* `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`].
**Default:** `false`.
* `keepAliveInitialDelay` {number} If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
**Default:** `0`.
* `requestListener` {Function}
* Returns: {http.Server}
Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically
added to the [`'request'`][] event.
```cjs
const http = require('http');
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!'
}));
});
server.listen(8000);
```
```cjs
const http = require('http');
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!'
}));
});
server.listen(8000);
```
## `http.get(options[, callback])`
## `http.get(url[, options][, callback])`
<!-- YAML
added: v0.3.6
changes:
- version: v10.9.0
pr-url: https://github.com/nodejs/node/pull/21616
description: The `url` parameter can now be passed along with a separate
`options` object.
- version: v7.5.0
pr-url: https://github.com/nodejs/node/pull/10638
description: The `options` parameter can be a WHATWG `URL` object.
-->
* `url` {string | URL}
* `options` {Object} Accepts the same `options` as
[`http.request()`][], with the `method` always set to `GET`.
Properties that are inherited from the prototype are ignored.
* `callback` {Function}
* Returns: {http.ClientRequest}
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
[`http.request()`][] is that it sets the method to GET and calls `req.end()`
automatically. The callback must take care to consume the response
data for reasons stated in [`http.ClientRequest`][] section.
The `callback` is invoked with a single argument that is an instance of
[`http.IncomingMessage`][].
JSON fetching example:
```js
http.get('http://localhost:8000/', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!'
}));
});
server.listen(8000);
```
## `http.globalAgent`
<!-- YAML
added: v0.5.9
-->
* {http.Agent}
Global instance of `Agent` which is used as the default for all HTTP client
requests.
## `http.maxHeaderSize`
<!-- YAML
added:
- v11.6.0
- v10.15.0
-->
* {number}
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16 KB. Configurable using the [`--max-http-header-size`][] CLI
option.
This can be overridden for servers and client requests by passing the
`maxHeaderSize` option.
## `http.request(options[, callback])`
## `http.request(url[, options][, callback])`
<!-- YAML
added: v0.3.6
changes:
- version:
- v16.7.0
- v14.18.0
pr-url: https://github.com/nodejs/node/pull/39310
description: When using a `URL` object parsed username and
password will now be properly URI decoded.
- version:
- v15.3.0
- v14.17.0
pr-url: https://github.com/nodejs/node/pull/36048
description: It is possible to abort a request with an AbortSignal.
- version:
- v13.8.0
- v12.15.0
- v10.19.0
pr-url: https://github.com/nodejs/node/pull/31448
description: The `insecureHTTPParser` option is supported now.
- version: v13.3.0
pr-url: https://github.com/nodejs/node/pull/30570
description: The `maxHeaderSize` option is supported now.
- version: v10.9.0
pr-url: https://github.com/nodejs/node/pull/21616
description: The `url` parameter can now be passed along with a separate
`options` object.
- version: v7.5.0
pr-url: https://github.com/nodejs/node/pull/10638
description: The `options` parameter can be a WHATWG `URL` object.
-->
* `url` {string | URL}
* `options` {Object}
* `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible
values:
* `undefined` (default): use [`http.globalAgent`][] for this host and port.
* `Agent` object: explicitly use the passed in `Agent`.
* `false`: causes a new `Agent` with default values to be used.
* `auth` {string} Basic authentication (`'user:password'`) to compute an
Authorization header.
* `createConnection` {Function} A function that produces a socket/stream to
use for the request when the `agent` option is not used. This can be used to
avoid creating a custom `Agent` class just to override the default
`createConnection` function. See [`agent.createConnection()`][] for more
details. Any [`Duplex`][] stream is a valid return value.
* `defaultPort` {number} Default port for the protocol. **Default:**
`agent.defaultPort` if an `Agent` is used, else `undefined`.
* `family` {number} IP address family to use when resolving `host` or
`hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and
v6 will be used.
* `headers` {Object} An object containing request headers.
* `hints` {number} Optional [`dns.lookup()` hints][].
* `host` {string} A domain name or IP address of the server to issue the
request to. **Default:** `'localhost'`.
* `hostname` {string} Alias for `host`. To support [`url.parse()`][],
`hostname` will be used if both `host` and `hostname` are specified.
* `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts
invalid HTTP headers when `true`. Using the insecure parser should be
avoided. See [`--insecure-http-parser`][] for more information.
**Default:** `false`
* `localAddress` {string} Local interface to bind for network connections.
* `localPort` {number} Local port to connect from.
* `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
* `maxHeaderSize` {number} Optionally overrides the value of
[`--max-http-header-size`][] (the maximum length of response headers in
bytes) for responses received from the server.
**Default:** 16384 (16 KB).
* `method` {string} A string specifying the HTTP request method. **Default:**
`'GET'`.
* `path` {string} Request path. Should include query string if any.
E.G. `'/index.html?page=12'`. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future. **Default:** `'/'`.
* `port` {number} Port of remote server. **Default:** `defaultPort` if set,
else `80`.
* `protocol` {string} Protocol to use. **Default:** `'http:'`.
* `setHost` {boolean}: Specifies whether or not to automatically add the
`Host` header. Defaults to `true`.
* `socketPath` {string} Unix domain socket. Cannot be used if one of `host`
or `port` is specified, as those specify a TCP Socket.
* `timeout` {number}: A number specifying the socket timeout in milliseconds.
This will set the timeout before the socket is connected.
* `signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing
request.
* `callback` {Function}
* Returns: {http.ClientRequest}
`options` in [`socket.connect()`][] are also supported.
Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.
`url` can be a string or a [`URL`][] object. If `url` is a
string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][]
object, it will be automatically converted to an ordinary `options` object.
If both `url` and `options` are specified, the objects are merged, with the
`options` properties taking precedence.
The optional `callback` parameter will be added as a one-time listener for
the [`'response'`][] event.
`http.request()` returns an instance of the [`http.ClientRequest`][]
class. The `ClientRequest` instance is a writable stream. If one needs to
upload a file with a POST request, then write to the `ClientRequest` object.
```js
const http = require('http');
const postData = JSON.stringify({
'msg': 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
```
In the example `req.end()` was called. With `http.request()` one
must always call `req.end()` to signify the end of the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
on the returned request object. As with all `'error'` events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
* Sending a 'Connection: keep-alive' will notify Node.js that the connection to
the server should be persisted until the next request.
* Sending a 'Content-Length' header will disable the default chunked encoding.
* Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', both a timeout and a listener
for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
information.
* Sending an Authorization header will override using the `auth` option
to compute basic authentication.
Example using a [`URL`][] as `options`:
```js
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
```
In a successful request, the following events will be emitted in the following
order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
(`'data'` will not be emitted at all if the response body is empty, for
instance, in most redirects)
* `'end'` on the `res` object
* `'close'`
In the case of a connection error, the following events will be emitted:
* `'socket'`
* `'error'`
* `'close'`
In the case of a premature connection close before the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
In the case of a premature connection close after the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (connection closed here)
* `'aborted'` on the `res` object
* `'error'` on the `res` object with an error with message
`'Error: aborted'` and code `'ECONNRESET'`.
* `'close'`
* `'close'` on the `res` object
If `req.destroy()` is called before a socket is assigned, the following
events will be emitted in the following order:
* (`req.destroy()` called here)
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
If `req.destroy()` is called before the connection succeeds, the following
events will be emitted in the following order:
* `'socket'`
* (`req.destroy()` called here)
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
If `req.destroy()` is called after the response is received, the following
events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (`req.destroy()` called here)
* `'aborted'` on the `res` object
* `'error'` on the `res` object with an error with message
`'Error: aborted'` and code `'ECONNRESET'`.
* `'close'`
* `'close'` on the `res` object
If `req.abort()` is called before a socket is assigned, the following
events will be emitted in the following order:
* (`req.abort()` called here)
* `'abort'`
* `'close'`
If `req.abort()` is called before the connection succeeds, the following
events will be emitted in the following order:
* `'socket'`
* (`req.abort()` called here)
* `'abort'`
* `'error'` with an error with message `'Error: socket hang up'` and code
`'ECONNRESET'`
* `'close'`
If `req.abort()` is called after the response is received, the following
events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (`req.abort()` called here)
* `'abort'`
* `'aborted'` on the `res` object
* `'error'` on the `res` object with an error with message
`'Error: aborted'` and code `'ECONNRESET'`.
* `'close'`
* `'close'` on the `res` object
Setting the `timeout` option or using the `setTimeout()` function will
not abort the request or do anything besides add a `'timeout'` event.
Passing an `AbortSignal` and then calling `abort` on the corresponding
`AbortController` will behave the same way as calling `.destroy()` on the
request itself.
## `http.validateHeaderName(name)`
<!-- YAML
added: v14.3.0
-->
* `name` {string}
Performs the low-level validations on the provided `name` that are done when
`res.setHeader(name, value)` is called.
Passing illegal value as `name` will result in a [`TypeError`][] being thrown,
identified by `code: 'ERR_INVALID_HTTP_TOKEN'`.
It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.
Examples:
Example:
```js
const { validateHeaderName } = require('http');
try {
validateHeaderName('');
} catch (err) {
err instanceof TypeError; // --> true
err.code; // --> 'ERR_INVALID_HTTP_TOKEN'
err.message; // --> 'Header name must be a valid HTTP token [""]'
}
```
## `http.validateHeaderValue(name, value)`
<!-- YAML
added: v14.3.0
-->
* `name` {string}
* `value` {any}
Performs the low-level validations on the provided `value` that are done when
`res.setHeader(name, value)` is called.
Passing illegal value as `value` will result in a [`TypeError`][] being thrown.
* Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`.
* Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`.
It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.
Examples:
```js
const { validateHeaderValue } = require('http');
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
err instanceof TypeError; // --> true
err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
err instanceof TypeError; // --> true
err.code === 'ERR_INVALID_CHAR'; // --> true
err.message; // --> 'Invalid character in header content ["x-my-header"]'
}
```
[RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt
[`'checkContinue'`]: #event-checkcontinue
[`'finish'`]: #event-finish
[`'request'`]: #event-request
[`'response'`]: #event-response
[`'upgrade'`]: #event-upgrade
[`--insecure-http-parser`]: cli.md#--insecure-http-parser
[`--max-http-header-size`]: cli.md#--max-http-header-sizesize
[`Agent`]: #class-httpagent
[`Buffer.byteLength()`]: buffer.md#static-method-bufferbytelengthstring-encoding
[`Duplex`]: stream.md#class-streamduplex
[`HPE_HEADER_OVERFLOW`]: errors.md#hpe_header_overflow
[`TypeError`]: errors.md#class-typeerror
[`URL`]: url.md#the-whatwg-url-api
[`agent.createConnection()`]: #agentcreateconnectionoptions-callback
[`agent.getName()`]: #agentgetnameoptions
[`destroy()`]: #agentdestroy
[`dns.lookup()`]: dns.md#dnslookuphostname-options-callback
[`dns.lookup()` hints]: dns.md#supported-getaddrinfo-flags
[`getHeader(name)`]: #requestgetheadername
[`http.Agent`]: #class-httpagent
[`http.ClientRequest`]: #class-httpclientrequest
[`http.IncomingMessage`]: #class-httpincomingmessage
[`http.ServerResponse`]: #class-httpserverresponse
[`http.Server`]: #class-httpserver
[`http.get()`]: #httpgetoptions-callback
[`http.globalAgent`]: #httpglobalagent
[`http.request()`]: #httprequestoptions-callback
[`message.headers`]: #messageheaders
[`message.socket`]: #messagesocket
[`net.Server.close()`]: net.md#serverclosecallback
[`net.Server`]: net.md#class-netserver
[`net.Socket`]: net.md#class-netsocket
[`net.createConnection()`]: net.md#netcreateconnectionoptions-connectlistener
[`new URL()`]: url.md#new-urlinput-base
[`outgoingMessage.socket`]: #outgoingmessagesocket
[`removeHeader(name)`]: #requestremoveheadername
[`request.destroy()`]: #requestdestroyerror
[`request.destroyed`]: #requestdestroyed
[`request.end()`]: #requestenddata-encoding-callback
[`request.flushHeaders()`]: #requestflushheaders
[`request.getHeader()`]: #requestgetheadername
[`request.setHeader()`]: #requestsetheadername-value
[`request.setTimeout()`]: #requestsettimeouttimeout-callback
[`request.socket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed
[`request.socket`]: #requestsocket
[`request.writableEnded`]: #requestwritableended
[`request.writableFinished`]: #requestwritablefinished
[`request.write(data, encoding)`]: #requestwritechunk-encoding-callback
[`response.end()`]: #responseenddata-encoding-callback
[`response.getHeader()`]: #responsegetheadername
[`response.setHeader()`]: #responsesetheadername-value
[`response.socket`]: #responsesocket
[`response.writableEnded`]: #responsewritableended
[`response.writableFinished`]: #responsewritablefinished
[`response.write()`]: #responsewritechunk-encoding-callback
[`response.write(data, encoding)`]: #responsewritechunk-encoding-callback
[`response.writeContinue()`]: #responsewritecontinue
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
[`server.headersTimeout`]: #serverheaderstimeout
[`server.keepAliveTimeout`]: #serverkeepalivetimeout
[`server.listen()`]: net.md#serverlisten
[`server.requestTimeout`]: #serverrequesttimeout
[`server.timeout`]: #servertimeout
[`setHeader(name, value)`]: #requestsetheadername-value
[`socket.connect()`]: net.md#socketconnectoptions-connectlistener
[`socket.setKeepAlive()`]: net.md#socketsetkeepaliveenable-initialdelay
[`socket.setNoDelay()`]: net.md#socketsetnodelaynodelay
[`socket.setTimeout()`]: net.md#socketsettimeouttimeout-callback
[`socket.unref()`]: net.md#socketunref
[`url.parse()`]: url.md#urlparseurlstring-parsequerystring-slashesdenotehost
[`writable.cork()`]: stream.md#writablecork
[`writable.destroy()`]: stream.md#writabledestroyerror
[`writable.destroyed`]: stream.md#writabledestroyed
[`writable.uncork()`]: stream.md#writableuncork
[initial delay]: net.md#socketsetkeepaliveenable-initialdelay
|