1# HTTP 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!-- source_link=lib/http.js --> 8 9To use the HTTP server and client one must `require('http')`. 10 11The HTTP interfaces in Node.js are designed to support many features 12of the protocol which have been traditionally difficult to use. 13In particular, large, possibly chunk-encoded, messages. The interface is 14careful to never buffer entire requests or responses, so the 15user is able to stream data. 16 17HTTP message headers are represented by an object like this: 18 19<!-- eslint-skip --> 20```js 21{ 'content-length': '123', 22 'content-type': 'text/plain', 23 'connection': 'keep-alive', 24 'host': 'mysite.com', 25 'accept': '*/*' } 26``` 27 28Keys are lowercased. Values are not modified. 29 30In order to support the full spectrum of possible HTTP applications, the Node.js 31HTTP API is very low-level. It deals with stream handling and message 32parsing only. It parses a message into headers and body but it does not 33parse the actual headers or the body. 34 35See [`message.headers`][] for details on how duplicate headers are handled. 36 37The raw headers as they were received are retained in the `rawHeaders` 38property, which is an array of `[key, value, key2, value2, ...]`. For 39example, the previous message header object might have a `rawHeaders` 40list like the following: 41 42<!-- eslint-disable semi --> 43```js 44[ 'ConTent-Length', '123456', 45 'content-LENGTH', '123', 46 'content-type', 'text/plain', 47 'CONNECTION', 'keep-alive', 48 'Host', 'mysite.com', 49 'accepT', '*/*' ] 50``` 51 52## Class: `http.Agent` 53<!-- YAML 54added: v0.3.4 55--> 56 57An `Agent` is responsible for managing connection persistence 58and reuse for HTTP clients. It maintains a queue of pending requests 59for a given host and port, reusing a single socket connection for each 60until the queue is empty, at which time the socket is either destroyed 61or put into a pool where it is kept to be used again for requests to the 62same host and port. Whether it is destroyed or pooled depends on the 63`keepAlive` [option](#http_new_agent_options). 64 65Pooled connections have TCP Keep-Alive enabled for them, but servers may 66still close idle connections, in which case they will be removed from the 67pool and a new connection will be made when a new HTTP request is made for 68that host and port. Servers may also refuse to allow multiple requests 69over the same connection, in which case the connection will have to be 70remade for every request and cannot be pooled. The `Agent` will still make 71the requests to that server, but each one will occur over a new connection. 72 73When a connection is closed by the client or the server, it is removed 74from the pool. Any unused sockets in the pool will be unrefed so as not 75to keep the Node.js process running when there are no outstanding requests. 76(see [`socket.unref()`][]). 77 78It is good practice, to [`destroy()`][] an `Agent` instance when it is no 79longer in use, because unused sockets consume OS resources. 80 81Sockets are removed from an agent when the socket emits either 82a `'close'` event or an `'agentRemove'` event. When intending to keep one 83HTTP request open for a long time without keeping it in the agent, something 84like the following may be done: 85 86```js 87http.get(options, (res) => { 88 // Do stuff 89}).on('socket', (socket) => { 90 socket.emit('agentRemove'); 91}); 92``` 93 94An agent may also be used for an individual request. By providing 95`{agent: false}` as an option to the `http.get()` or `http.request()` 96functions, a one-time use `Agent` with default options will be used 97for the client connection. 98 99`agent:false`: 100 101```js 102http.get({ 103 hostname: 'localhost', 104 port: 80, 105 path: '/', 106 agent: false // Create a new agent just for this one request 107}, (res) => { 108 // Do stuff with response 109}); 110``` 111 112### `new Agent([options])` 113<!-- YAML 114added: v0.3.4 115changes: 116 - version: v14.17.0 117 pr-url: https://github.com/nodejs/node/pull/36685 118 description: Change the default scheduling from 'fifo' to 'lifo'. 119 - version: v14.5.0 120 pr-url: https://github.com/nodejs/node/pull/33617 121 description: Add `maxTotalSockets` option to agent constructor. 122 - version: v14.5.0 123 pr-url: https://github.com/nodejs/node/pull/33278 124 description: Add `scheduling` option to specify the free socket 125 scheduling strategy. 126--> 127 128* `options` {Object} Set of configurable options to set on the agent. 129 Can have the following fields: 130 * `keepAlive` {boolean} Keep sockets around even when there are no 131 outstanding requests, so they can be used for future requests without 132 having to reestablish a TCP connection. Not to be confused with the 133 `keep-alive` value of the `Connection` header. The `Connection: keep-alive` 134 header is always sent when using an agent except when the `Connection` 135 header is explicitly specified or when the `keepAlive` and `maxSockets` 136 options are respectively set to `false` and `Infinity`, in which case 137 `Connection: close` will be used. **Default:** `false`. 138 * `keepAliveMsecs` {number} When using the `keepAlive` option, specifies 139 the [initial delay](net.md#net_socket_setkeepalive_enable_initialdelay) 140 for TCP Keep-Alive packets. Ignored when the 141 `keepAlive` option is `false` or `undefined`. **Default:** `1000`. 142 * `maxSockets` {number} Maximum number of sockets to allow per host. 143 If the same host opens multiple concurrent connections, each request 144 will use new socket until the `maxSockets` value is reached. 145 If the host attempts to open more connections than `maxSockets`, 146 the additional requests will enter into a pending request queue, and 147 will enter active connection state when an existing connection terminates. 148 This makes sure there are at most `maxSockets` active connections at 149 any point in time, from a given host. 150 **Default:** `Infinity`. 151 * `maxTotalSockets` {number} Maximum number of sockets allowed for 152 all hosts in total. Each request will use a new socket 153 until the maximum is reached. 154 **Default:** `Infinity`. 155 * `maxFreeSockets` {number} Maximum number of sockets to leave open 156 in a free state. Only relevant if `keepAlive` is set to `true`. 157 **Default:** `256`. 158 * `scheduling` {string} Scheduling strategy to apply when picking 159 the next free socket to use. It can be `'fifo'` or `'lifo'`. 160 The main difference between the two scheduling strategies is that `'lifo'` 161 selects the most recently used socket, while `'fifo'` selects 162 the least recently used socket. 163 In case of a low rate of request per second, the `'lifo'` scheduling 164 will lower the risk of picking a socket that might have been closed 165 by the server due to inactivity. 166 In case of a high rate of request per second, 167 the `'fifo'` scheduling will maximize the number of open sockets, 168 while the `'lifo'` scheduling will keep it as low as possible. 169 **Default:** `'lifo'`. 170 * `timeout` {number} Socket timeout in milliseconds. 171 This will set the timeout when the socket is created. 172 173`options` in [`socket.connect()`][] are also supported. 174 175The default [`http.globalAgent`][] that is used by [`http.request()`][] has all 176of these values set to their respective defaults. 177 178To configure any of them, a custom [`http.Agent`][] instance must be created. 179 180```js 181const http = require('http'); 182const keepAliveAgent = new http.Agent({ keepAlive: true }); 183options.agent = keepAliveAgent; 184http.request(options, onResponseCallback); 185``` 186 187### `agent.createConnection(options[, callback])` 188<!-- YAML 189added: v0.11.4 190--> 191 192* `options` {Object} Options containing connection details. Check 193 [`net.createConnection()`][] for the format of the options 194* `callback` {Function} Callback function that receives the created socket 195* Returns: {stream.Duplex} 196 197Produces a socket/stream to be used for HTTP requests. 198 199By default, this function is the same as [`net.createConnection()`][]. However, 200custom agents may override this method in case greater flexibility is desired. 201 202A socket/stream can be supplied in one of two ways: by returning the 203socket/stream from this function, or by passing the socket/stream to `callback`. 204 205This method is guaranteed to return an instance of the {net.Socket} class, 206a subclass of {stream.Duplex}, unless the user specifies a socket 207type other than {net.Socket}. 208 209`callback` has a signature of `(err, stream)`. 210 211### `agent.keepSocketAlive(socket)` 212<!-- YAML 213added: v8.1.0 214--> 215 216* `socket` {stream.Duplex} 217 218Called when `socket` is detached from a request and could be persisted by the 219`Agent`. Default behavior is to: 220 221```js 222socket.setKeepAlive(true, this.keepAliveMsecs); 223socket.unref(); 224return true; 225``` 226 227This method can be overridden by a particular `Agent` subclass. If this 228method returns a falsy value, the socket will be destroyed instead of persisting 229it for use with the next request. 230 231The `socket` argument can be an instance of {net.Socket}, a subclass of 232{stream.Duplex}. 233 234### `agent.reuseSocket(socket, request)` 235<!-- YAML 236added: v8.1.0 237--> 238 239* `socket` {stream.Duplex} 240* `request` {http.ClientRequest} 241 242Called when `socket` is attached to `request` after being persisted because of 243the keep-alive options. Default behavior is to: 244 245```js 246socket.ref(); 247``` 248 249This method can be overridden by a particular `Agent` subclass. 250 251The `socket` argument can be an instance of {net.Socket}, a subclass of 252{stream.Duplex}. 253 254### `agent.destroy()` 255<!-- YAML 256added: v0.11.4 257--> 258 259Destroy any sockets that are currently in use by the agent. 260 261It is usually not necessary to do this. However, if using an 262agent with `keepAlive` enabled, then it is best to explicitly shut down 263the agent when it is no longer needed. Otherwise, 264sockets might stay open for quite a long time before the server 265terminates them. 266 267### `agent.freeSockets` 268<!-- YAML 269added: v0.11.4 270--> 271 272* {Object} 273 274An object which contains arrays of sockets currently awaiting use by 275the agent when `keepAlive` is enabled. Do not modify. 276 277Sockets in the `freeSockets` list will be automatically destroyed and 278removed from the array on `'timeout'`. 279 280### `agent.getName(options)` 281<!-- YAML 282added: v0.11.4 283--> 284 285* `options` {Object} A set of options providing information for name generation 286 * `host` {string} A domain name or IP address of the server to issue the 287 request to 288 * `port` {number} Port of remote server 289 * `localAddress` {string} Local interface to bind for network connections 290 when issuing the request 291 * `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`. 292* Returns: {string} 293 294Get a unique name for a set of request options, to determine whether a 295connection can be reused. For an HTTP agent, this returns 296`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, 297the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options 298that determine socket reusability. 299 300### `agent.maxFreeSockets` 301<!-- YAML 302added: v0.11.7 303--> 304 305* {number} 306 307By default set to 256. For agents with `keepAlive` enabled, this 308sets the maximum number of sockets that will be left open in the free 309state. 310 311### `agent.maxSockets` 312<!-- YAML 313added: v0.3.6 314--> 315 316* {number} 317 318By default set to `Infinity`. Determines how many concurrent sockets the agent 319can have open per origin. Origin is the returned value of [`agent.getName()`][]. 320 321### `agent.maxTotalSockets` 322<!-- YAML 323added: v14.5.0 324--> 325 326* {number} 327 328By default set to `Infinity`. Determines how many concurrent sockets the agent 329can have open. Unlike `maxSockets`, this parameter applies across all origins. 330 331### `agent.requests` 332<!-- YAML 333added: v0.5.9 334--> 335 336* {Object} 337 338An object which contains queues of requests that have not yet been assigned to 339sockets. Do not modify. 340 341### `agent.sockets` 342<!-- YAML 343added: v0.3.6 344--> 345 346* {Object} 347 348An object which contains arrays of sockets currently in use by the 349agent. Do not modify. 350 351## Class: `http.ClientRequest` 352<!-- YAML 353added: v0.1.17 354--> 355 356* Extends: {Stream} 357 358This object is created internally and returned from [`http.request()`][]. It 359represents an _in-progress_ request whose header has already been queued. The 360header is still mutable using the [`setHeader(name, value)`][], 361 [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will 362be sent along with the first data chunk or when calling [`request.end()`][]. 363 364To get the response, add a listener for [`'response'`][] to the request object. 365[`'response'`][] will be emitted from the request object when the response 366headers have been received. The [`'response'`][] event is executed with one 367argument which is an instance of [`http.IncomingMessage`][]. 368 369During the [`'response'`][] event, one can add listeners to the 370response object; particularly to listen for the `'data'` event. 371 372If no [`'response'`][] handler is added, then the response will be 373entirely discarded. However, if a [`'response'`][] event handler is added, 374then the data from the response object **must** be consumed, either by 375calling `response.read()` whenever there is a `'readable'` event, or 376by adding a `'data'` handler, or by calling the `.resume()` method. 377Until the data is consumed, the `'end'` event will not fire. Also, until 378the data is read it will consume memory that can eventually lead to a 379'process out of memory' error. 380 381Unlike the `request` object, if the response closes prematurely, the 382`response` object does not emit an `'error'` event but instead emits the 383`'aborted'` event. 384 385Node.js does not check whether Content-Length and the length of the 386body which has been transmitted are equal or not. 387 388### Event: `'abort'` 389<!-- YAML 390added: v1.4.1 391--> 392 393Emitted when the request has been aborted by the client. This event is only 394emitted on the first call to `abort()`. 395 396### Event: `'connect'` 397<!-- YAML 398added: v0.7.0 399--> 400 401* `response` {http.IncomingMessage} 402* `socket` {stream.Duplex} 403* `head` {Buffer} 404 405Emitted each time a server responds to a request with a `CONNECT` method. If 406this event is not being listened for, clients receiving a `CONNECT` method will 407have their connections closed. 408 409This event is guaranteed to be passed an instance of the {net.Socket} class, 410a subclass of {stream.Duplex}, unless the user specifies a socket 411type other than {net.Socket}. 412 413A client and server pair demonstrating how to listen for the `'connect'` event: 414 415```js 416const http = require('http'); 417const net = require('net'); 418const { URL } = require('url'); 419 420// Create an HTTP tunneling proxy 421const proxy = http.createServer((req, res) => { 422 res.writeHead(200, { 'Content-Type': 'text/plain' }); 423 res.end('okay'); 424}); 425proxy.on('connect', (req, clientSocket, head) => { 426 // Connect to an origin server 427 const { port, hostname } = new URL(`http://${req.url}`); 428 const serverSocket = net.connect(port || 80, hostname, () => { 429 clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 430 'Proxy-agent: Node.js-Proxy\r\n' + 431 '\r\n'); 432 serverSocket.write(head); 433 serverSocket.pipe(clientSocket); 434 clientSocket.pipe(serverSocket); 435 }); 436}); 437 438// Now that proxy is running 439proxy.listen(1337, '127.0.0.1', () => { 440 441 // Make a request to a tunneling proxy 442 const options = { 443 port: 1337, 444 host: '127.0.0.1', 445 method: 'CONNECT', 446 path: 'www.google.com:80' 447 }; 448 449 const req = http.request(options); 450 req.end(); 451 452 req.on('connect', (res, socket, head) => { 453 console.log('got connected!'); 454 455 // Make a request over an HTTP tunnel 456 socket.write('GET / HTTP/1.1\r\n' + 457 'Host: www.google.com:80\r\n' + 458 'Connection: close\r\n' + 459 '\r\n'); 460 socket.on('data', (chunk) => { 461 console.log(chunk.toString()); 462 }); 463 socket.on('end', () => { 464 proxy.close(); 465 }); 466 }); 467}); 468``` 469 470### Event: `'continue'` 471<!-- YAML 472added: v0.3.2 473--> 474 475Emitted when the server sends a '100 Continue' HTTP response, usually because 476the request contained 'Expect: 100-continue'. This is an instruction that 477the client should send the request body. 478 479### Event: `'information'` 480<!-- YAML 481added: v10.0.0 482--> 483 484* `info` {Object} 485 * `httpVersion` {string} 486 * `httpVersionMajor` {integer} 487 * `httpVersionMinor` {integer} 488 * `statusCode` {integer} 489 * `statusMessage` {string} 490 * `headers` {Object} 491 * `rawHeaders` {string[]} 492 493Emitted when the server sends a 1xx intermediate response (excluding 101 494Upgrade). The listeners of this event will receive an object containing the 495HTTP version, status code, status message, key-value headers object, 496and array with the raw header names followed by their respective values. 497 498```js 499const http = require('http'); 500 501const options = { 502 host: '127.0.0.1', 503 port: 8080, 504 path: '/length_request' 505}; 506 507// Make a request 508const req = http.request(options); 509req.end(); 510 511req.on('information', (info) => { 512 console.log(`Got information prior to main response: ${info.statusCode}`); 513}); 514``` 515 516101 Upgrade statuses do not fire this event due to their break from the 517traditional HTTP request/response chain, such as web sockets, in-place TLS 518upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the 519[`'upgrade'`][] event instead. 520 521### Event: `'response'` 522<!-- YAML 523added: v0.1.0 524--> 525 526* `response` {http.IncomingMessage} 527 528Emitted when a response is received to this request. This event is emitted only 529once. 530 531### Event: `'socket'` 532<!-- YAML 533added: v0.5.3 534--> 535 536* `socket` {stream.Duplex} 537 538This event is guaranteed to be passed an instance of the {net.Socket} class, 539a subclass of {stream.Duplex}, unless the user specifies a socket 540type other than {net.Socket}. 541 542### Event: `'timeout'` 543<!-- YAML 544added: v0.7.8 545--> 546 547Emitted when the underlying socket times out from inactivity. This only notifies 548that the socket has been idle. The request must be aborted manually. 549 550See also: [`request.setTimeout()`][]. 551 552### Event: `'upgrade'` 553<!-- YAML 554added: v0.1.94 555--> 556 557* `response` {http.IncomingMessage} 558* `socket` {stream.Duplex} 559* `head` {Buffer} 560 561Emitted each time a server responds to a request with an upgrade. If this 562event is not being listened for and the response status code is 101 Switching 563Protocols, clients receiving an upgrade header will have their connections 564closed. 565 566This event is guaranteed to be passed an instance of the {net.Socket} class, 567a subclass of {stream.Duplex}, unless the user specifies a socket 568type other than {net.Socket}. 569 570A client server pair demonstrating how to listen for the `'upgrade'` event. 571 572```js 573const http = require('http'); 574 575// Create an HTTP server 576const server = http.createServer((req, res) => { 577 res.writeHead(200, { 'Content-Type': 'text/plain' }); 578 res.end('okay'); 579}); 580server.on('upgrade', (req, socket, head) => { 581 socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 582 'Upgrade: WebSocket\r\n' + 583 'Connection: Upgrade\r\n' + 584 '\r\n'); 585 586 socket.pipe(socket); // echo back 587}); 588 589// Now that server is running 590server.listen(1337, '127.0.0.1', () => { 591 592 // make a request 593 const options = { 594 port: 1337, 595 host: '127.0.0.1', 596 headers: { 597 'Connection': 'Upgrade', 598 'Upgrade': 'websocket' 599 } 600 }; 601 602 const req = http.request(options); 603 req.end(); 604 605 req.on('upgrade', (res, socket, upgradeHead) => { 606 console.log('got upgraded!'); 607 socket.end(); 608 process.exit(0); 609 }); 610}); 611``` 612 613### `request.abort()` 614<!-- YAML 615added: v0.3.8 616deprecated: v14.1.0 617--> 618 619> Stability: 0 - Deprecated: Use [`request.destroy()`][] instead. 620 621Marks the request as aborting. Calling this will cause remaining data 622in the response to be dropped and the socket to be destroyed. 623 624### `request.aborted` 625<!-- YAML 626added: v0.11.14 627changes: 628 - version: v11.0.0 629 pr-url: https://github.com/nodejs/node/pull/20230 630 description: The `aborted` property is no longer a timestamp number. 631--> 632 633* {boolean} 634 635The `request.aborted` property will be `true` if the request has 636been aborted. 637 638### `request.connection` 639<!-- YAML 640added: v0.3.0 641deprecated: v13.0.0 642--> 643 644> Stability: 0 - Deprecated. Use [`request.socket`][]. 645 646* {stream.Duplex} 647 648See [`request.socket`][]. 649 650### `request.end([data[, encoding]][, callback])` 651<!-- YAML 652added: v0.1.90 653changes: 654 - version: v10.0.0 655 pr-url: https://github.com/nodejs/node/pull/18780 656 description: This method now returns a reference to `ClientRequest`. 657--> 658 659* `data` {string|Buffer} 660* `encoding` {string} 661* `callback` {Function} 662* Returns: {this} 663 664Finishes sending the request. If any parts of the body are 665unsent, it will flush them to the stream. If the request is 666chunked, this will send the terminating `'0\r\n\r\n'`. 667 668If `data` is specified, it is equivalent to calling 669[`request.write(data, encoding)`][] followed by `request.end(callback)`. 670 671If `callback` is specified, it will be called when the request stream 672is finished. 673 674### `request.destroy([error])` 675<!-- YAML 676added: v0.3.0 677changes: 678 - version: v14.5.0 679 pr-url: https://github.com/nodejs/node/pull/32789 680 description: The function returns `this` for consistency with other Readable 681 streams. 682--> 683 684* `error` {Error} Optional, an error to emit with `'error'` event. 685* Returns: {this} 686 687Destroy the request. Optionally emit an `'error'` event, 688and emit a `'close'` event. Calling this will cause remaining data 689in the response to be dropped and the socket to be destroyed. 690 691See [`writable.destroy()`][] for further details. 692 693#### `request.destroyed` 694<!-- YAML 695added: v14.1.0 696--> 697 698* {boolean} 699 700Is `true` after [`request.destroy()`][] has been called. 701 702See [`writable.destroyed`][] for further details. 703 704### `request.finished` 705<!-- YAML 706added: v0.0.1 707deprecated: 708 - v13.4.0 709 - v12.16.0 710--> 711 712> Stability: 0 - Deprecated. Use [`request.writableEnded`][]. 713 714* {boolean} 715 716The `request.finished` property will be `true` if [`request.end()`][] 717has been called. `request.end()` will automatically be called if the 718request was initiated via [`http.get()`][]. 719 720### `request.flushHeaders()` 721<!-- YAML 722added: v1.6.0 723--> 724 725Flushes the request headers. 726 727For efficiency reasons, Node.js normally buffers the request headers until 728`request.end()` is called or the first chunk of request data is written. It 729then tries to pack the request headers and data into a single TCP packet. 730 731That's usually desired (it saves a TCP round-trip), but not when the first 732data is not sent until possibly much later. `request.flushHeaders()` bypasses 733the optimization and kickstarts the request. 734 735### `request.getHeader(name)` 736<!-- YAML 737added: v1.6.0 738--> 739 740* `name` {string} 741* Returns: {any} 742 743Reads out a header on the request. The name is case-insensitive. 744The type of the return value depends on the arguments provided to 745[`request.setHeader()`][]. 746 747```js 748request.setHeader('content-type', 'text/html'); 749request.setHeader('Content-Length', Buffer.byteLength(body)); 750request.setHeader('Cookie', ['type=ninja', 'language=javascript']); 751const contentType = request.getHeader('Content-Type'); 752// 'contentType' is 'text/html' 753const contentLength = request.getHeader('Content-Length'); 754// 'contentLength' is of type number 755const cookie = request.getHeader('Cookie'); 756// 'cookie' is of type string[] 757``` 758 759### `request.getRawHeaderNames()` 760<!-- YAML 761added: v14.17.0 762--> 763 764* Returns: {string[]} 765 766Returns an array containing the unique names of the current outgoing raw 767headers. Header names are returned with their exact casing being set. 768 769```js 770request.setHeader('Foo', 'bar'); 771request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 772 773const headerNames = request.getRawHeaderNames(); 774// headerNames === ['Foo', 'Set-Cookie'] 775``` 776 777### `request.maxHeadersCount` 778 779* {number} **Default:** `2000` 780 781Limits maximum response headers count. If set to 0, no limit will be applied. 782 783### `request.path` 784<!-- YAML 785added: v0.4.0 786--> 787 788* {string} The request path. 789 790### `request.method` 791<!-- YAML 792added: v0.1.97 793--> 794 795* {string} The request method. 796 797### `request.host` 798<!-- YAML 799added: v14.5.0 800--> 801 802* {string} The request host. 803 804### `request.protocol` 805<!-- YAML 806added: v14.5.0 807--> 808 809* {string} The request protocol. 810 811### `request.removeHeader(name)` 812<!-- YAML 813added: v1.6.0 814--> 815 816* `name` {string} 817 818Removes a header that's already defined into headers object. 819 820```js 821request.removeHeader('Content-Type'); 822``` 823 824### `request.reusedSocket` 825<!-- YAML 826added: 827 - v13.0.0 828 - v12.16.0 829--> 830 831* {boolean} Whether the request is send through a reused socket. 832 833When sending request through a keep-alive enabled agent, the underlying socket 834might be reused. But if server closes connection at unfortunate time, client 835may run into a 'ECONNRESET' error. 836 837```js 838const http = require('http'); 839 840// Server has a 5 seconds keep-alive timeout by default 841http 842 .createServer((req, res) => { 843 res.write('hello\n'); 844 res.end(); 845 }) 846 .listen(3000); 847 848setInterval(() => { 849 // Adapting a keep-alive agent 850 http.get('http://localhost:3000', { agent }, (res) => { 851 res.on('data', (data) => { 852 // Do nothing 853 }); 854 }); 855}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout 856``` 857 858By marking a request whether it reused socket or not, we can do 859automatic error retry base on it. 860 861```js 862const http = require('http'); 863const agent = new http.Agent({ keepAlive: true }); 864 865function retriableRequest() { 866 const req = http 867 .get('http://localhost:3000', { agent }, (res) => { 868 // ... 869 }) 870 .on('error', (err) => { 871 // Check if retry is needed 872 if (req.reusedSocket && err.code === 'ECONNRESET') { 873 retriableRequest(); 874 } 875 }); 876} 877 878retriableRequest(); 879``` 880 881### `request.setHeader(name, value)` 882<!-- YAML 883added: v1.6.0 884--> 885 886* `name` {string} 887* `value` {any} 888 889Sets a single header value for headers object. If this header already exists in 890the to-be-sent headers, its value will be replaced. Use an array of strings 891here to send multiple headers with the same name. Non-string values will be 892stored without modification. Therefore, [`request.getHeader()`][] may return 893non-string values. However, the non-string values will be converted to strings 894for network transmission. 895 896```js 897request.setHeader('Content-Type', 'application/json'); 898``` 899 900or 901 902```js 903request.setHeader('Cookie', ['type=ninja', 'language=javascript']); 904``` 905 906### `request.setNoDelay([noDelay])` 907<!-- YAML 908added: v0.5.9 909--> 910 911* `noDelay` {boolean} 912 913Once a socket is assigned to this request and is connected 914[`socket.setNoDelay()`][] will be called. 915 916### `request.setSocketKeepAlive([enable][, initialDelay])` 917<!-- YAML 918added: v0.5.9 919--> 920 921* `enable` {boolean} 922* `initialDelay` {number} 923 924Once a socket is assigned to this request and is connected 925[`socket.setKeepAlive()`][] will be called. 926 927### `request.setTimeout(timeout[, callback])` 928<!-- YAML 929added: v0.5.9 930changes: 931 - version: v9.0.0 932 pr-url: https://github.com/nodejs/node/pull/8895 933 description: Consistently set socket timeout only when the socket connects. 934--> 935 936* `timeout` {number} Milliseconds before a request times out. 937* `callback` {Function} Optional function to be called when a timeout occurs. 938 Same as binding to the `'timeout'` event. 939* Returns: {http.ClientRequest} 940 941Once a socket is assigned to this request and is connected 942[`socket.setTimeout()`][] will be called. 943 944### `request.socket` 945<!-- YAML 946added: v0.3.0 947--> 948 949* {stream.Duplex} 950 951Reference to the underlying socket. Usually users will not want to access 952this property. In particular, the socket will not emit `'readable'` events 953because of how the protocol parser attaches to the socket. 954 955```js 956const http = require('http'); 957const options = { 958 host: 'www.google.com', 959}; 960const req = http.get(options); 961req.end(); 962req.once('response', (res) => { 963 const ip = req.socket.localAddress; 964 const port = req.socket.localPort; 965 console.log(`Your IP address is ${ip} and your source port is ${port}.`); 966 // Consume response object 967}); 968``` 969 970This property is guaranteed to be an instance of the {net.Socket} class, 971a subclass of {stream.Duplex}, unless the user specified a socket 972type other than {net.Socket}. 973 974### `request.writableEnded` 975<!-- YAML 976added: v12.9.0 977--> 978 979* {boolean} 980 981Is `true` after [`request.end()`][] has been called. This property 982does not indicate whether the data has been flushed, for this use 983[`request.writableFinished`][] instead. 984 985### `request.writableFinished` 986<!-- YAML 987added: v12.7.0 988--> 989 990* {boolean} 991 992Is `true` if all data has been flushed to the underlying system, immediately 993before the [`'finish'`][] event is emitted. 994 995### `request.write(chunk[, encoding][, callback])` 996<!-- YAML 997added: v0.1.29 998--> 999 1000* `chunk` {string|Buffer} 1001* `encoding` {string} 1002* `callback` {Function} 1003* Returns: {boolean} 1004 1005Sends a chunk of the body. This method can be called multiple times. If no 1006`Content-Length` is set, data will automatically be encoded in HTTP Chunked 1007transfer encoding, so that server knows when the data ends. The 1008`Transfer-Encoding: chunked` header is added. Calling [`request.end()`][] 1009is necessary to finish sending the request. 1010 1011The `encoding` argument is optional and only applies when `chunk` is a string. 1012Defaults to `'utf8'`. 1013 1014The `callback` argument is optional and will be called when this chunk of data 1015is flushed, but only if the chunk is non-empty. 1016 1017Returns `true` if the entire data was flushed successfully to the kernel 1018buffer. Returns `false` if all or part of the data was queued in user memory. 1019`'drain'` will be emitted when the buffer is free again. 1020 1021When `write` function is called with empty string or buffer, it does 1022nothing and waits for more input. 1023 1024## Class: `http.Server` 1025<!-- YAML 1026added: v0.1.17 1027--> 1028 1029* Extends: {net.Server} 1030 1031### Event: `'checkContinue'` 1032<!-- YAML 1033added: v0.3.0 1034--> 1035 1036* `request` {http.IncomingMessage} 1037* `response` {http.ServerResponse} 1038 1039Emitted each time a request with an HTTP `Expect: 100-continue` is received. 1040If this event is not listened for, the server will automatically respond 1041with a `100 Continue` as appropriate. 1042 1043Handling this event involves calling [`response.writeContinue()`][] if the 1044client should continue to send the request body, or generating an appropriate 1045HTTP response (e.g. 400 Bad Request) if the client should not continue to send 1046the request body. 1047 1048When this event is emitted and handled, the [`'request'`][] event will 1049not be emitted. 1050 1051### Event: `'checkExpectation'` 1052<!-- YAML 1053added: v5.5.0 1054--> 1055 1056* `request` {http.IncomingMessage} 1057* `response` {http.ServerResponse} 1058 1059Emitted each time a request with an HTTP `Expect` header is received, where the 1060value is not `100-continue`. If this event is not listened for, the server will 1061automatically respond with a `417 Expectation Failed` as appropriate. 1062 1063When this event is emitted and handled, the [`'request'`][] event will 1064not be emitted. 1065 1066### Event: `'clientError'` 1067<!-- YAML 1068added: v0.1.94 1069changes: 1070 - version: v12.0.0 1071 pr-url: https://github.com/nodejs/node/pull/25605 1072 description: The default behavior will return a 431 Request Header 1073 Fields Too Large if a HPE_HEADER_OVERFLOW error occurs. 1074 - version: v9.4.0 1075 pr-url: https://github.com/nodejs/node/pull/17672 1076 description: The `rawPacket` is the current buffer that just parsed. Adding 1077 this buffer to the error object of `'clientError'` event is to 1078 make it possible that developers can log the broken packet. 1079 - version: v6.0.0 1080 pr-url: https://github.com/nodejs/node/pull/4557 1081 description: The default action of calling `.destroy()` on the `socket` 1082 will no longer take place if there are listeners attached 1083 for `'clientError'`. 1084--> 1085 1086* `exception` {Error} 1087* `socket` {stream.Duplex} 1088 1089If a client connection emits an `'error'` event, it will be forwarded here. 1090Listener of this event is responsible for closing/destroying the underlying 1091socket. For example, one may wish to more gracefully close the socket with a 1092custom HTTP response instead of abruptly severing the connection. 1093 1094This event is guaranteed to be passed an instance of the {net.Socket} class, 1095a subclass of {stream.Duplex}, unless the user specifies a socket 1096type other than {net.Socket}. 1097 1098Default behavior is to try close the socket with a HTTP '400 Bad Request', 1099or a HTTP '431 Request Header Fields Too Large' in the case of a 1100[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable or has already 1101written data it is immediately destroyed. 1102 1103`socket` is the [`net.Socket`][] object that the error originated from. 1104 1105```js 1106const http = require('http'); 1107 1108const server = http.createServer((req, res) => { 1109 res.end(); 1110}); 1111server.on('clientError', (err, socket) => { 1112 socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); 1113}); 1114server.listen(8000); 1115``` 1116 1117When the `'clientError'` event occurs, there is no `request` or `response` 1118object, so any HTTP response sent, including response headers and payload, 1119*must* be written directly to the `socket` object. Care must be taken to 1120ensure the response is a properly formatted HTTP response message. 1121 1122`err` is an instance of `Error` with two extra columns: 1123 1124* `bytesParsed`: the bytes count of request packet that Node.js may have parsed 1125 correctly; 1126* `rawPacket`: the raw packet of current request. 1127 1128In some cases, the client has already received the response and/or the socket 1129has already been destroyed, like in case of `ECONNRESET` errors. Before 1130trying to send data to the socket, it is better to check that it is still 1131writable. 1132 1133```js 1134server.on('clientError', (err, socket) => { 1135 if (err.code === 'ECONNRESET' || !socket.writable) { 1136 return; 1137 } 1138 1139 socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); 1140}); 1141``` 1142 1143### Event: `'close'` 1144<!-- YAML 1145added: v0.1.4 1146--> 1147 1148Emitted when the server closes. 1149 1150### Event: `'connect'` 1151<!-- YAML 1152added: v0.7.0 1153--> 1154 1155* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in 1156 the [`'request'`][] event 1157* `socket` {stream.Duplex} Network socket between the server and client 1158* `head` {Buffer} The first packet of the tunneling stream (may be empty) 1159 1160Emitted each time a client requests an HTTP `CONNECT` method. If this event is 1161not listened for, then clients requesting a `CONNECT` method will have their 1162connections closed. 1163 1164This event is guaranteed to be passed an instance of the {net.Socket} class, 1165a subclass of {stream.Duplex}, unless the user specifies a socket 1166type other than {net.Socket}. 1167 1168After this event is emitted, the request's socket will not have a `'data'` 1169event listener, meaning it will need to be bound in order to handle data 1170sent to the server on that socket. 1171 1172### Event: `'connection'` 1173<!-- YAML 1174added: v0.1.0 1175--> 1176 1177* `socket` {stream.Duplex} 1178 1179This event is emitted when a new TCP stream is established. `socket` is 1180typically an object of type [`net.Socket`][]. Usually users will not want to 1181access this event. In particular, the socket will not emit `'readable'` events 1182because of how the protocol parser attaches to the socket. The `socket` can 1183also be accessed at `request.socket`. 1184 1185This event can also be explicitly emitted by users to inject connections 1186into the HTTP server. In that case, any [`Duplex`][] stream can be passed. 1187 1188If `socket.setTimeout()` is called here, the timeout will be replaced with 1189`server.keepAliveTimeout` when the socket has served a request (if 1190`server.keepAliveTimeout` is non-zero). 1191 1192This event is guaranteed to be passed an instance of the {net.Socket} class, 1193a subclass of {stream.Duplex}, unless the user specifies a socket 1194type other than {net.Socket}. 1195 1196### Event: `'request'` 1197<!-- YAML 1198added: v0.1.0 1199--> 1200 1201* `request` {http.IncomingMessage} 1202* `response` {http.ServerResponse} 1203 1204Emitted each time there is a request. There may be multiple requests 1205per connection (in the case of HTTP Keep-Alive connections). 1206 1207### Event: `'upgrade'` 1208<!-- YAML 1209added: v0.1.94 1210changes: 1211 - version: v10.0.0 1212 pr-url: https://github.com/nodejs/node/pull/19981 1213 description: Not listening to this event no longer causes the socket 1214 to be destroyed if a client sends an Upgrade header. 1215--> 1216 1217* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in 1218 the [`'request'`][] event 1219* `socket` {stream.Duplex} Network socket between the server and client 1220* `head` {Buffer} The first packet of the upgraded stream (may be empty) 1221 1222Emitted each time a client requests an HTTP upgrade. Listening to this event 1223is optional and clients cannot insist on a protocol change. 1224 1225After this event is emitted, the request's socket will not have a `'data'` 1226event listener, meaning it will need to be bound in order to handle data 1227sent to the server on that socket. 1228 1229This event is guaranteed to be passed an instance of the {net.Socket} class, 1230a subclass of {stream.Duplex}, unless the user specifies a socket 1231type other than {net.Socket}. 1232 1233### `server.close([callback])` 1234<!-- YAML 1235added: v0.1.90 1236--> 1237 1238* `callback` {Function} 1239 1240Stops the server from accepting new connections. See [`net.Server.close()`][]. 1241 1242### `server.headersTimeout` 1243<!-- YAML 1244added: 1245 - v11.3.0 1246 - v10.14.0 1247--> 1248 1249* {number} **Default:** `60000` 1250 1251Limit the amount of time the parser will wait to receive the complete HTTP 1252headers. 1253 1254In case of inactivity, the rules defined in [`server.timeout`][] apply. However, 1255that inactivity based timeout would still allow the connection to be kept open 1256if the headers are being sent very slowly (by default, up to a byte per 2 1257minutes). In order to prevent this, whenever header data arrives an additional 1258check is made that more than `server.headersTimeout` milliseconds has not 1259passed since the connection was established. If the check fails, a `'timeout'` 1260event is emitted on the server object, and (by default) the socket is destroyed. 1261See [`server.timeout`][] for more information on how timeout behavior can be 1262customized. 1263 1264### `server.listen()` 1265 1266Starts the HTTP server listening for connections. 1267This method is identical to [`server.listen()`][] from [`net.Server`][]. 1268 1269### `server.listening` 1270<!-- YAML 1271added: v5.7.0 1272--> 1273 1274* {boolean} Indicates whether or not the server is listening for connections. 1275 1276### `server.maxHeadersCount` 1277<!-- YAML 1278added: v0.7.0 1279--> 1280 1281* {number} **Default:** `2000` 1282 1283Limits maximum incoming headers count. If set to 0, no limit will be applied. 1284 1285### `server.requestTimeout` 1286<!-- YAML 1287added: v14.11.0 1288--> 1289 1290* {number} **Default:** `0` 1291 1292Sets the timeout value in milliseconds for receiving the entire request from 1293the client. 1294 1295If the timeout expires, the server responds with status 408 without 1296forwarding the request to the request listener and then closes the connection. 1297 1298It must be set to a non-zero value (e.g. 120 seconds) to protect against 1299potential Denial-of-Service attacks in case the server is deployed without a 1300reverse proxy in front. 1301 1302### `server.setTimeout([msecs][, callback])` 1303<!-- YAML 1304added: v0.9.12 1305changes: 1306 - version: v13.0.0 1307 pr-url: https://github.com/nodejs/node/pull/27558 1308 description: The default timeout changed from 120s to 0 (no timeout). 1309--> 1310 1311* `msecs` {number} **Default:** 0 (no timeout) 1312* `callback` {Function} 1313* Returns: {http.Server} 1314 1315Sets the timeout value for sockets, and emits a `'timeout'` event on 1316the Server object, passing the socket as an argument, if a timeout 1317occurs. 1318 1319If there is a `'timeout'` event listener on the Server object, then it 1320will be called with the timed-out socket as an argument. 1321 1322By default, the Server does not timeout sockets. However, if a callback 1323is assigned to the Server's `'timeout'` event, timeouts must be handled 1324explicitly. 1325 1326### `server.timeout` 1327<!-- YAML 1328added: v0.9.12 1329changes: 1330 - version: v13.0.0 1331 pr-url: https://github.com/nodejs/node/pull/27558 1332 description: The default timeout changed from 120s to 0 (no timeout). 1333--> 1334 1335* {number} Timeout in milliseconds. **Default:** 0 (no timeout) 1336 1337The number of milliseconds of inactivity before a socket is presumed 1338to have timed out. 1339 1340A value of `0` will disable the timeout behavior on incoming connections. 1341 1342The socket timeout logic is set up on connection, so changing this 1343value only affects new connections to the server, not any existing connections. 1344 1345### `server.keepAliveTimeout` 1346<!-- YAML 1347added: v8.0.0 1348--> 1349 1350* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds). 1351 1352The number of milliseconds of inactivity a server needs to wait for additional 1353incoming data, after it has finished writing the last response, before a socket 1354will be destroyed. If the server receives new data before the keep-alive 1355timeout has fired, it will reset the regular inactivity timeout, i.e., 1356[`server.timeout`][]. 1357 1358A value of `0` will disable the keep-alive timeout behavior on incoming 1359connections. 1360A value of `0` makes the http server behave similarly to Node.js versions prior 1361to 8.0.0, which did not have a keep-alive timeout. 1362 1363The socket timeout logic is set up on connection, so changing this value only 1364affects new connections to the server, not any existing connections. 1365 1366## Class: `http.ServerResponse` 1367<!-- YAML 1368added: v0.1.17 1369--> 1370 1371* Extends: {Stream} 1372 1373This object is created internally by an HTTP server, not by the user. It is 1374passed as the second parameter to the [`'request'`][] event. 1375 1376### Event: `'close'` 1377<!-- YAML 1378added: v0.6.7 1379--> 1380 1381Indicates that the response is completed, or its underlying connection was 1382terminated prematurely (before the response completion). 1383 1384### Event: `'finish'` 1385<!-- YAML 1386added: v0.3.6 1387--> 1388 1389Emitted when the response has been sent. More specifically, this event is 1390emitted when the last segment of the response headers and body have been 1391handed off to the operating system for transmission over the network. It 1392does not imply that the client has received anything yet. 1393 1394### `response.addTrailers(headers)` 1395<!-- YAML 1396added: v0.3.0 1397--> 1398 1399* `headers` {Object} 1400 1401This method adds HTTP trailing headers (a header but at the end of the 1402message) to the response. 1403 1404Trailers will **only** be emitted if chunked encoding is used for the 1405response; if it is not (e.g. if the request was HTTP/1.0), they will 1406be silently discarded. 1407 1408HTTP requires the `Trailer` header to be sent in order to 1409emit trailers, with a list of the header fields in its value. E.g., 1410 1411```js 1412response.writeHead(200, { 'Content-Type': 'text/plain', 1413 'Trailer': 'Content-MD5' }); 1414response.write(fileData); 1415response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); 1416response.end(); 1417``` 1418 1419Attempting to set a header field name or value that contains invalid characters 1420will result in a [`TypeError`][] being thrown. 1421 1422### `response.connection` 1423<!-- YAML 1424added: v0.3.0 1425deprecated: v13.0.0 1426--> 1427 1428> Stability: 0 - Deprecated. Use [`response.socket`][]. 1429 1430* {stream.Duplex} 1431 1432See [`response.socket`][]. 1433 1434### `response.cork()` 1435<!-- YAML 1436added: 1437 - v13.2.0 1438 - v12.16.0 1439--> 1440 1441See [`writable.cork()`][]. 1442 1443### `response.end([data[, encoding]][, callback])` 1444<!-- YAML 1445added: v0.1.90 1446changes: 1447 - version: v10.0.0 1448 pr-url: https://github.com/nodejs/node/pull/18780 1449 description: This method now returns a reference to `ServerResponse`. 1450--> 1451 1452* `data` {string|Buffer} 1453* `encoding` {string} 1454* `callback` {Function} 1455* Returns: {this} 1456 1457This method signals to the server that all of the response headers and body 1458have been sent; that server should consider this message complete. 1459The method, `response.end()`, MUST be called on each response. 1460 1461If `data` is specified, it is similar in effect to calling 1462[`response.write(data, encoding)`][] followed by `response.end(callback)`. 1463 1464If `callback` is specified, it will be called when the response stream 1465is finished. 1466 1467### `response.finished` 1468<!-- YAML 1469added: v0.0.2 1470deprecated: 1471 - v13.4.0 1472 - v12.16.0 1473--> 1474 1475> Stability: 0 - Deprecated. Use [`response.writableEnded`][]. 1476 1477* {boolean} 1478 1479The `response.finished` property will be `true` if [`response.end()`][] 1480has been called. 1481 1482### `response.flushHeaders()` 1483<!-- YAML 1484added: v1.6.0 1485--> 1486 1487Flushes the response headers. See also: [`request.flushHeaders()`][]. 1488 1489### `response.getHeader(name)` 1490<!-- YAML 1491added: v0.4.0 1492--> 1493 1494* `name` {string} 1495* Returns: {any} 1496 1497Reads out a header that's already been queued but not sent to the client. 1498The name is case-insensitive. The type of the return value depends 1499on the arguments provided to [`response.setHeader()`][]. 1500 1501```js 1502response.setHeader('Content-Type', 'text/html'); 1503response.setHeader('Content-Length', Buffer.byteLength(body)); 1504response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 1505const contentType = response.getHeader('content-type'); 1506// contentType is 'text/html' 1507const contentLength = response.getHeader('Content-Length'); 1508// contentLength is of type number 1509const setCookie = response.getHeader('set-cookie'); 1510// setCookie is of type string[] 1511``` 1512 1513### `response.getHeaderNames()` 1514<!-- YAML 1515added: v7.7.0 1516--> 1517 1518* Returns: {string[]} 1519 1520Returns an array containing the unique names of the current outgoing headers. 1521All header names are lowercase. 1522 1523```js 1524response.setHeader('Foo', 'bar'); 1525response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 1526 1527const headerNames = response.getHeaderNames(); 1528// headerNames === ['foo', 'set-cookie'] 1529``` 1530 1531### `response.getHeaders()` 1532<!-- YAML 1533added: v7.7.0 1534--> 1535 1536* Returns: {Object} 1537 1538Returns a shallow copy of the current outgoing headers. Since a shallow copy 1539is used, array values may be mutated without additional calls to various 1540header-related http module methods. The keys of the returned object are the 1541header names and the values are the respective header values. All header names 1542are lowercase. 1543 1544The object returned by the `response.getHeaders()` method _does not_ 1545prototypically inherit from the JavaScript `Object`. This means that typical 1546`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others 1547are not defined and *will not work*. 1548 1549```js 1550response.setHeader('Foo', 'bar'); 1551response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 1552 1553const headers = response.getHeaders(); 1554// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 1555``` 1556 1557### `response.hasHeader(name)` 1558<!-- YAML 1559added: v7.7.0 1560--> 1561 1562* `name` {string} 1563* Returns: {boolean} 1564 1565Returns `true` if the header identified by `name` is currently set in the 1566outgoing headers. The header name matching is case-insensitive. 1567 1568```js 1569const hasContentType = response.hasHeader('content-type'); 1570``` 1571 1572### `response.headersSent` 1573<!-- YAML 1574added: v0.9.3 1575--> 1576 1577* {boolean} 1578 1579Boolean (read-only). True if headers were sent, false otherwise. 1580 1581### `response.removeHeader(name)` 1582<!-- YAML 1583added: v0.4.0 1584--> 1585 1586* `name` {string} 1587 1588Removes a header that's queued for implicit sending. 1589 1590```js 1591response.removeHeader('Content-Encoding'); 1592``` 1593 1594### `response.sendDate` 1595<!-- YAML 1596added: v0.7.5 1597--> 1598 1599* {boolean} 1600 1601When true, the Date header will be automatically generated and sent in 1602the response if it is not already present in the headers. Defaults to true. 1603 1604This should only be disabled for testing; HTTP requires the Date header 1605in responses. 1606 1607### `response.setHeader(name, value)` 1608<!-- YAML 1609added: v0.4.0 1610--> 1611 1612* `name` {string} 1613* `value` {any} 1614* Returns: {http.ServerResponse} 1615 1616Returns the response object. 1617 1618Sets a single header value for implicit headers. If this header already exists 1619in the to-be-sent headers, its value will be replaced. Use an array of strings 1620here to send multiple headers with the same name. Non-string values will be 1621stored without modification. Therefore, [`response.getHeader()`][] may return 1622non-string values. However, the non-string values will be converted to strings 1623for network transmission. The same response object is returned to the caller, 1624to enable call chaining. 1625 1626```js 1627response.setHeader('Content-Type', 'text/html'); 1628``` 1629 1630or 1631 1632```js 1633response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 1634``` 1635 1636Attempting to set a header field name or value that contains invalid characters 1637will result in a [`TypeError`][] being thrown. 1638 1639When headers have been set with [`response.setHeader()`][], they will be merged 1640with any headers passed to [`response.writeHead()`][], with the headers passed 1641to [`response.writeHead()`][] given precedence. 1642 1643```js 1644// Returns content-type = text/plain 1645const server = http.createServer((req, res) => { 1646 res.setHeader('Content-Type', 'text/html'); 1647 res.setHeader('X-Foo', 'bar'); 1648 res.writeHead(200, { 'Content-Type': 'text/plain' }); 1649 res.end('ok'); 1650}); 1651``` 1652 1653If [`response.writeHead()`][] method is called and this method has not been 1654called, it will directly write the supplied header values onto the network 1655channel without caching internally, and the [`response.getHeader()`][] on the 1656header will not yield the expected result. If progressive population of headers 1657is desired with potential future retrieval and modification, use 1658[`response.setHeader()`][] instead of [`response.writeHead()`][]. 1659 1660### `response.setTimeout(msecs[, callback])` 1661<!-- YAML 1662added: v0.9.12 1663--> 1664 1665* `msecs` {number} 1666* `callback` {Function} 1667* Returns: {http.ServerResponse} 1668 1669Sets the Socket's timeout value to `msecs`. If a callback is 1670provided, then it is added as a listener on the `'timeout'` event on 1671the response object. 1672 1673If no `'timeout'` listener is added to the request, the response, or 1674the server, then sockets are destroyed when they time out. If a handler is 1675assigned to the request, the response, or the server's `'timeout'` events, 1676timed out sockets must be handled explicitly. 1677 1678### `response.socket` 1679<!-- YAML 1680added: v0.3.0 1681--> 1682 1683* {stream.Duplex} 1684 1685Reference to the underlying socket. Usually users will not want to access 1686this property. In particular, the socket will not emit `'readable'` events 1687because of how the protocol parser attaches to the socket. After 1688`response.end()`, the property is nulled. 1689 1690```js 1691const http = require('http'); 1692const server = http.createServer((req, res) => { 1693 const ip = res.socket.remoteAddress; 1694 const port = res.socket.remotePort; 1695 res.end(`Your IP address is ${ip} and your source port is ${port}.`); 1696}).listen(3000); 1697``` 1698 1699This property is guaranteed to be an instance of the {net.Socket} class, 1700a subclass of {stream.Duplex}, unless the user specified a socket 1701type other than {net.Socket}. 1702 1703### `response.statusCode` 1704<!-- YAML 1705added: v0.4.0 1706--> 1707 1708* {number} **Default:** `200` 1709 1710When using implicit headers (not calling [`response.writeHead()`][] explicitly), 1711this property controls the status code that will be sent to the client when 1712the headers get flushed. 1713 1714```js 1715response.statusCode = 404; 1716``` 1717 1718After response header was sent to the client, this property indicates the 1719status code which was sent out. 1720 1721### `response.statusMessage` 1722<!-- YAML 1723added: v0.11.8 1724--> 1725 1726* {string} 1727 1728When using implicit headers (not calling [`response.writeHead()`][] explicitly), 1729this property controls the status message that will be sent to the client when 1730the headers get flushed. If this is left as `undefined` then the standard 1731message for the status code will be used. 1732 1733```js 1734response.statusMessage = 'Not found'; 1735``` 1736 1737After response header was sent to the client, this property indicates the 1738status message which was sent out. 1739 1740### `response.uncork()` 1741<!-- YAML 1742added: 1743 - v13.2.0 1744 - v12.16.0 1745--> 1746 1747See [`writable.uncork()`][]. 1748 1749### `response.writableEnded` 1750<!-- YAML 1751added: v12.9.0 1752--> 1753 1754* {boolean} 1755 1756Is `true` after [`response.end()`][] has been called. This property 1757does not indicate whether the data has been flushed, for this use 1758[`response.writableFinished`][] instead. 1759 1760### `response.writableFinished` 1761<!-- YAML 1762added: v12.7.0 1763--> 1764 1765* {boolean} 1766 1767Is `true` if all data has been flushed to the underlying system, immediately 1768before the [`'finish'`][] event is emitted. 1769 1770### `response.write(chunk[, encoding][, callback])` 1771<!-- YAML 1772added: v0.1.29 1773--> 1774 1775* `chunk` {string|Buffer} 1776* `encoding` {string} **Default:** `'utf8'` 1777* `callback` {Function} 1778* Returns: {boolean} 1779 1780If this method is called and [`response.writeHead()`][] has not been called, 1781it will switch to implicit header mode and flush the implicit headers. 1782 1783This sends a chunk of the response body. This method may 1784be called multiple times to provide successive parts of the body. 1785 1786In the `http` module, the response body is omitted when the 1787request is a HEAD request. Similarly, the `204` and `304` responses 1788_must not_ include a message body. 1789 1790`chunk` can be a string or a buffer. If `chunk` is a string, 1791the second parameter specifies how to encode it into a byte stream. 1792`callback` will be called when this chunk of data is flushed. 1793 1794This is the raw HTTP body and has nothing to do with higher-level multi-part 1795body encodings that may be used. 1796 1797The first time [`response.write()`][] is called, it will send the buffered 1798header information and the first chunk of the body to the client. The second 1799time [`response.write()`][] is called, Node.js assumes data will be streamed, 1800and sends the new data separately. That is, the response is buffered up to the 1801first chunk of the body. 1802 1803Returns `true` if the entire data was flushed successfully to the kernel 1804buffer. Returns `false` if all or part of the data was queued in user memory. 1805`'drain'` will be emitted when the buffer is free again. 1806 1807### `response.writeContinue()` 1808<!-- YAML 1809added: v0.3.0 1810--> 1811 1812Sends a HTTP/1.1 100 Continue message to the client, indicating that 1813the request body should be sent. See the [`'checkContinue'`][] event on 1814`Server`. 1815 1816### `response.writeHead(statusCode[, statusMessage][, headers])` 1817<!-- YAML 1818added: v0.1.30 1819changes: 1820 - version: v14.14.0 1821 pr-url: https://github.com/nodejs/node/pull/35274 1822 description: Allow passing headers as an array. 1823 - version: 1824 - v11.10.0 1825 - v10.17.0 1826 pr-url: https://github.com/nodejs/node/pull/25974 1827 description: Return `this` from `writeHead()` to allow chaining with 1828 `end()`. 1829 - version: 1830 - v5.11.0 1831 - v4.4.5 1832 pr-url: https://github.com/nodejs/node/pull/6291 1833 description: A `RangeError` is thrown if `statusCode` is not a number in 1834 the range `[100, 999]`. 1835--> 1836 1837* `statusCode` {number} 1838* `statusMessage` {string} 1839* `headers` {Object|Array} 1840* Returns: {http.ServerResponse} 1841 1842Sends a response header to the request. The status code is a 3-digit HTTP 1843status code, like `404`. The last argument, `headers`, are the response headers. 1844Optionally one can give a human-readable `statusMessage` as the second 1845argument. 1846 1847`headers` may be an `Array` where the keys and values are in the same list. 1848It is *not* a list of tuples. So, the even-numbered offsets are key values, 1849and the odd-numbered offsets are the associated values. The array is in the same 1850format as `request.rawHeaders`. 1851 1852Returns a reference to the `ServerResponse`, so that calls can be chained. 1853 1854```js 1855const body = 'hello world'; 1856response 1857 .writeHead(200, { 1858 'Content-Length': Buffer.byteLength(body), 1859 'Content-Type': 'text/plain' 1860 }) 1861 .end(body); 1862``` 1863 1864This method must only be called once on a message and it must 1865be called before [`response.end()`][] is called. 1866 1867If [`response.write()`][] or [`response.end()`][] are called before calling 1868this, the implicit/mutable headers will be calculated and call this function. 1869 1870When headers have been set with [`response.setHeader()`][], they will be merged 1871with any headers passed to [`response.writeHead()`][], with the headers passed 1872to [`response.writeHead()`][] given precedence. 1873 1874If this method is called and [`response.setHeader()`][] has not been called, 1875it will directly write the supplied header values onto the network channel 1876without caching internally, and the [`response.getHeader()`][] on the header 1877will not yield the expected result. If progressive population of headers is 1878desired with potential future retrieval and modification, use 1879[`response.setHeader()`][] instead. 1880 1881```js 1882// Returns content-type = text/plain 1883const server = http.createServer((req, res) => { 1884 res.setHeader('Content-Type', 'text/html'); 1885 res.setHeader('X-Foo', 'bar'); 1886 res.writeHead(200, { 'Content-Type': 'text/plain' }); 1887 res.end('ok'); 1888}); 1889``` 1890 1891`Content-Length` is given in bytes, not characters. Use 1892[`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js 1893does not check whether `Content-Length` and the length of the body which has 1894been transmitted are equal or not. 1895 1896Attempting to set a header field name or value that contains invalid characters 1897will result in a [`TypeError`][] being thrown. 1898 1899### `response.writeProcessing()` 1900<!-- YAML 1901added: v10.0.0 1902--> 1903 1904Sends a HTTP/1.1 102 Processing message to the client, indicating that 1905the request body should be sent. 1906 1907## Class: `http.IncomingMessage` 1908<!-- YAML 1909added: v0.1.17 1910changes: 1911 - version: 1912 - v13.1.0 1913 - v12.16.0 1914 pr-url: https://github.com/nodejs/node/pull/30135 1915 description: The `readableHighWaterMark` value mirrors that of the socket. 1916--> 1917 1918* Extends: {stream.Readable} 1919 1920An `IncomingMessage` object is created by [`http.Server`][] or 1921[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][] 1922and [`'response'`][] event respectively. It may be used to access response 1923status, headers and data. 1924 1925### Event: `'aborted'` 1926<!-- YAML 1927added: v0.3.8 1928--> 1929 1930Emitted when the request has been aborted. 1931 1932### Event: `'close'` 1933<!-- YAML 1934added: v0.4.2 1935--> 1936 1937Indicates that the underlying connection was closed. 1938 1939### `message.aborted` 1940<!-- YAML 1941added: v10.1.0 1942--> 1943 1944* {boolean} 1945 1946The `message.aborted` property will be `true` if the request has 1947been aborted. 1948 1949### `message.complete` 1950<!-- YAML 1951added: v0.3.0 1952--> 1953 1954* {boolean} 1955 1956The `message.complete` property will be `true` if a complete HTTP message has 1957been received and successfully parsed. 1958 1959This property is particularly useful as a means of determining if a client or 1960server fully transmitted a message before a connection was terminated: 1961 1962```js 1963const req = http.request({ 1964 host: '127.0.0.1', 1965 port: 8080, 1966 method: 'POST' 1967}, (res) => { 1968 res.resume(); 1969 res.on('end', () => { 1970 if (!res.complete) 1971 console.error( 1972 'The connection was terminated while the message was still being sent'); 1973 }); 1974}); 1975``` 1976 1977### `message.destroy([error])` 1978<!-- YAML 1979added: v0.3.0 1980changes: 1981 - version: v14.5.0 1982 pr-url: https://github.com/nodejs/node/pull/32789 1983 description: The function returns `this` for consistency with other Readable 1984 streams. 1985--> 1986 1987* `error` {Error} 1988* Returns: {this} 1989 1990Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` 1991is provided, an `'error'` event is emitted on the socket and `error` is passed 1992as an argument to any listeners on the event. 1993 1994### `message.headers` 1995<!-- YAML 1996added: v0.1.5 1997--> 1998 1999* {Object} 2000 2001The request/response headers object. 2002 2003Key-value pairs of header names and values. Header names are lower-cased. 2004 2005```js 2006// Prints something like: 2007// 2008// { 'user-agent': 'curl/7.22.0', 2009// host: '127.0.0.1:8000', 2010// accept: '*/*' } 2011console.log(request.headers); 2012``` 2013 2014Duplicates in raw headers are handled in the following ways, depending on the 2015header name: 2016 2017* Duplicates of `age`, `authorization`, `content-length`, `content-type`, 2018 `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, 2019 `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, 2020 `retry-after`, `server`, or `user-agent` are discarded. 2021* `set-cookie` is always an array. Duplicates are added to the array. 2022* For duplicate `cookie` headers, the values are joined together with '; '. 2023* For all other headers, the values are joined together with ', '. 2024 2025### `message.httpVersion` 2026<!-- YAML 2027added: v0.1.1 2028--> 2029 2030* {string} 2031 2032In case of server request, the HTTP version sent by the client. In the case of 2033client response, the HTTP version of the connected-to server. 2034Probably either `'1.1'` or `'1.0'`. 2035 2036Also `message.httpVersionMajor` is the first integer and 2037`message.httpVersionMinor` is the second. 2038 2039### `message.method` 2040<!-- YAML 2041added: v0.1.1 2042--> 2043 2044* {string} 2045 2046**Only valid for request obtained from [`http.Server`][].** 2047 2048The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. 2049 2050### `message.rawHeaders` 2051<!-- YAML 2052added: v0.11.6 2053--> 2054 2055* {string[]} 2056 2057The raw request/response headers list exactly as they were received. 2058 2059The keys and values are in the same list. It is *not* a 2060list of tuples. So, the even-numbered offsets are key values, and the 2061odd-numbered offsets are the associated values. 2062 2063Header names are not lowercased, and duplicates are not merged. 2064 2065```js 2066// Prints something like: 2067// 2068// [ 'user-agent', 2069// 'this is invalid because there can be only one', 2070// 'User-Agent', 2071// 'curl/7.22.0', 2072// 'Host', 2073// '127.0.0.1:8000', 2074// 'ACCEPT', 2075// '*/*' ] 2076console.log(request.rawHeaders); 2077``` 2078 2079### `message.rawTrailers` 2080<!-- YAML 2081added: v0.11.6 2082--> 2083 2084* {string[]} 2085 2086The raw request/response trailer keys and values exactly as they were 2087received. Only populated at the `'end'` event. 2088 2089### `message.setTimeout(msecs[, callback])` 2090<!-- YAML 2091added: v0.5.9 2092--> 2093 2094* `msecs` {number} 2095* `callback` {Function} 2096* Returns: {http.IncomingMessage} 2097 2098Calls `message.socket.setTimeout(msecs, callback)`. 2099 2100### `message.socket` 2101<!-- YAML 2102added: v0.3.0 2103--> 2104 2105* {stream.Duplex} 2106 2107The [`net.Socket`][] object associated with the connection. 2108 2109With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the 2110client's authentication details. 2111 2112This property is guaranteed to be an instance of the {net.Socket} class, 2113a subclass of {stream.Duplex}, unless the user specified a socket 2114type other than {net.Socket}. 2115 2116### `message.statusCode` 2117<!-- YAML 2118added: v0.1.1 2119--> 2120 2121* {number} 2122 2123**Only valid for response obtained from [`http.ClientRequest`][].** 2124 2125The 3-digit HTTP response status code. E.G. `404`. 2126 2127### `message.statusMessage` 2128<!-- YAML 2129added: v0.11.10 2130--> 2131 2132* {string} 2133 2134**Only valid for response obtained from [`http.ClientRequest`][].** 2135 2136The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server 2137Error`. 2138 2139### `message.trailers` 2140<!-- YAML 2141added: v0.3.0 2142--> 2143 2144* {Object} 2145 2146The request/response trailers object. Only populated at the `'end'` event. 2147 2148### `message.url` 2149<!-- YAML 2150added: v0.1.90 2151--> 2152 2153* {string} 2154 2155**Only valid for request obtained from [`http.Server`][].** 2156 2157Request URL string. This contains only the URL that is present in the actual 2158HTTP request. Take the following request: 2159 2160```http 2161GET /status?name=ryan HTTP/1.1 2162Accept: text/plain 2163``` 2164 2165To parse the URL into its parts: 2166 2167```js 2168new URL(request.url, `http://${request.headers.host}`); 2169``` 2170 2171When `request.url` is `'/status?name=ryan'` and 2172`request.headers.host` is `'localhost:3000'`: 2173 2174```console 2175$ node 2176> new URL(request.url, `http://${request.headers.host}`) 2177URL { 2178 href: 'http://localhost:3000/status?name=ryan', 2179 origin: 'http://localhost:3000', 2180 protocol: 'http:', 2181 username: '', 2182 password: '', 2183 host: 'localhost:3000', 2184 hostname: 'localhost', 2185 port: '3000', 2186 pathname: '/status', 2187 search: '?name=ryan', 2188 searchParams: URLSearchParams { 'name' => 'ryan' }, 2189 hash: '' 2190} 2191``` 2192 2193## Class: `http.OutgoingMessage` 2194<!-- YAML 2195added: v0.1.17 2196--> 2197 2198* Extends: {Stream} 2199 2200This class serves as the parent class of [`http.ClientRequest`][] 2201and [`http.ServerResponse`][]. It is an abstract of outgoing message from 2202the perspective of the participants of HTTP transaction. 2203 2204### Event: `drain` 2205<!-- YAML 2206added: v0.3.6 2207--> 2208 2209Emitted when the buffer of the message is free again. 2210 2211### Event: `finish` 2212<!-- YAML 2213added: v0.1.17 2214--> 2215 2216Emitted when the transmission is finished successfully. 2217 2218### Event: `prefinish` 2219<!-- YAML 2220added: v0.11.6 2221--> 2222 2223Emitted when `outgoingMessage.end` was called. 2224When the event is emitted, all data has been processed but not necessarily 2225completely flushed. 2226 2227### `outgoingMessage.addTrailers(headers)` 2228<!-- YAML 2229added: v0.3.0 2230--> 2231 2232* `headers` {Object} 2233 2234Adds HTTP trailers (headers but at the end of the message) to the message. 2235 2236Trailers are **only** be emitted if the message is chunked encoded. If not, 2237the trailer will be silently discarded. 2238 2239HTTP requires the `Trailer` header to be sent to emit trailers, 2240with a list of header fields in its value, e.g. 2241 2242```js 2243message.writeHead(200, { 'Content-Type': 'text/plain', 2244 'Trailer': 'Content-MD5' }); 2245message.write(fileData); 2246message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); 2247message.end(); 2248``` 2249 2250Attempting to set a header field name or value that contains invalid characters 2251will result in a `TypeError` being thrown. 2252 2253### `outgoingMessage.connection` 2254<!-- YAML 2255added: v0.3.0 2256deprecated: v14.17.1 2257--> 2258 2259> Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead. 2260 2261Aliases of `outgoingMessage.socket` 2262### `outgoingMessage.cork()` 2263<!-- YAML 2264added: v14.0.0 2265--> 2266 2267See [`writable.cork()`][]. 2268 2269### `outgoingMessage.destroy([error])` 2270<!-- YAML 2271added: v0.3.0 2272--> 2273 2274* `error` {Error} Optional, an error to emit with `error` event 2275* Returns: {this} 2276 2277Destroys the message. Once a socket is associated with the message 2278and is connected, that socket will be destroyed as well. 2279 2280### `outgoingMessage.end(chunk[, encoding][, callback])` 2281<!-- YAML 2282added: v0.1.90 2283changes: 2284 - version: v0.11.6 2285 description: add `callback` argument. 2286--> 2287 2288* `chunk` {string | Buffer} 2289* `encoding` {string} Optional, **Default**: `utf-8` 2290* `callback` {Function} Optional 2291* Returns: {this} 2292 2293Finishes the outgoing message. If any parts of the body are unsent, it will 2294flush them to the underlying system. If the message is chunked, it will 2295send the terminating chunk `0\r\n\r\n`, and send the trailer (if any). 2296 2297If `chunk` is specified, it is equivalent to call 2298`outgoingMessage.write(chunk, encoding)`, followed by 2299`outgoingMessage.end(callback)`. 2300 2301If `callback` is provided, it will be called when the message is finished. 2302(equivalent to the callback to event `finish`) 2303 2304### `outgoingMessage.flushHeaders()` 2305<!-- YAML 2306added: v1.6.0 2307--> 2308 2309Compulsorily flushes the message headers 2310 2311For efficiency reason, Node.js normally buffers the message headers 2312until `outgoingMessage.end()` is called or the first chunk of message data 2313is written. It then tries to pack the headers and data into a single TCP 2314packet. 2315 2316It is usually desired (it saves a TCP round-trip), but not when the first 2317data is not sent until possibly much later. `outgoingMessage.flushHeaders()` 2318bypasses the optimization and kickstarts the request. 2319 2320### `outgoingMessage.getHeader(name)` 2321<!-- YAML 2322added: v0.4.0 2323--> 2324 2325* `name` {string} Name of header 2326* Returns {string | undefined} 2327 2328Gets the value of HTTP header with the given name. If such a name doesn't 2329exist in message, it will be `undefined`. 2330 2331### `outgoingMessage.getHeaderNames()` 2332<!-- YAML 2333added: v8.0.0 2334--> 2335 2336* Returns {string[]} 2337 2338Returns an array of names of headers of the outgoing outgoingMessage. All 2339names are lowercase. 2340 2341### `outgoingMessage.getHeaders()` 2342<!-- YAML 2343added: v8.0.0 2344--> 2345 2346* Returns: {Object} 2347 2348Returns a shallow copy of the current outgoing headers. Since a shallow 2349copy is used, array values may be mutated without additional calls to 2350various header-related HTTP module methods. The keys of the returned 2351object are the header names and the values are the respective header 2352values. All header names are lowercase. 2353 2354The object returned by the `outgoingMessage.getHeaders()` method does 2355not prototypically inherit from the JavaScript Object. This means that 2356typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, 2357and others are not defined and will not work. 2358 2359```js 2360outgoingMessage.setHeader('Foo', 'bar'); 2361outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 2362 2363const headers = outgoingMessage.getHeaders(); 2364// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 2365``` 2366 2367### `outgoingMessage.hasHeader(name)` 2368<!-- YAML 2369added: v8.0.0 2370--> 2371 2372* `name` {string} 2373* Returns {boolean} 2374 2375Returns `true` if the header identified by `name` is currently set in the 2376outgoing headers. The header name is case-insensitive. 2377 2378```js 2379const hasContentType = outgoingMessage.hasHeader('content-type'); 2380``` 2381 2382### `outgoingMessage.headersSent` 2383<!-- YAML 2384added: v0.9.3 2385--> 2386 2387* {boolean} 2388 2389Read-only. `true` if the headers were sent, otherwise `false`. 2390 2391### `outgoingMessage.pipe()` 2392<!-- YAML 2393added: v9.0.0 2394--> 2395 2396Overrides the pipe method of legacy `Stream` which is the parent class of 2397`http.outgoingMessage`. 2398 2399Since `OutgoingMessage` should be a write-only stream, 2400call this function will throw an `Error`. Thus, it disabled the pipe method 2401it inherits from `Stream`. 2402 2403The User should not call this function directly. 2404 2405### `outgoingMessage.removeHeader()` 2406<!-- YAML 2407added: v0.4.0 2408--> 2409 2410Removes a header that is queued for implicit sending. 2411 2412```js 2413outgoingMessage.removeHeader('Content-Encoding'); 2414``` 2415 2416### `outgoingMessage.setHeader(name, value)` 2417<!-- YAML 2418added: v0.4.0 2419--> 2420 2421* `name` {string} Header name 2422* `value` {string} Header value 2423* Returns: {this} 2424 2425Sets a single header value for the header object. 2426 2427### `outgoingMessage.setTimeout(msesc[, callback])` 2428<!-- YAML 2429added: v0.9.12 2430--> 2431 2432* `msesc` {number} 2433* `callback` {Function} Optional function to be called when a timeout 2434occurs, Same as binding to the `timeout` event. 2435* Returns: {this} 2436 2437Once a socket is associated with the message and is connected, 2438[`socket.setTimeout()`][] will be called with `msecs` as the first parameter. 2439 2440### `outgoingMessage.socket` 2441<!-- YAML 2442added: v0.3.0 2443--> 2444 2445* {stream.Duplex} 2446 2447Reference to the underlying socket. Usually, users will not want to access 2448this property. 2449 2450After calling `outgoingMessage.end()`, this property will be nulled. 2451 2452### `outgoingMessage.uncork()` 2453<!-- YAML 2454added: v14.0.0 2455--> 2456 2457See [`writable.uncork()`][] 2458 2459### `outgoingMessage.writableCorked` 2460<!-- YAML 2461added: v14.0.0 2462--> 2463 2464* {number} 2465 2466This `outgoingMessage.writableCorked` will return the time how many 2467`outgoingMessage.cork()` have been called. 2468 2469### `outgoingMessage.writableEnded` 2470<!-- YAML 2471added: v13.0.0 2472--> 2473 2474* {boolean} 2475 2476Readonly, `true` if `outgoingMessage.end()` has been called. Noted that 2477this property does not reflect whether the data has been flush. For that 2478purpose, use `message.writableFinished` instead. 2479 2480### `outgoingMessage.writableFinished` 2481<!-- YAML 2482added: v13.0.0 2483--> 2484 2485* {boolean} 2486 2487Readonly. `true` if all data has been flushed to the underlying system. 2488 2489### `outgoingMessage.writableHighWaterMark` 2490<!-- YAML 2491added: v13.0.0 2492--> 2493 2494* {number} 2495 2496This `outgoingMessage.writableHighWaterMark` will be the `highWaterMark` of 2497underlying socket if socket exists. Else, it would be the default 2498`highWaterMark`. 2499 2500`highWaterMark` is the maximum amount of data that can be potentially 2501buffered by the socket. 2502 2503### `outgoingMessage.writableLength` 2504<!-- YAML 2505added: v13.0.0 2506--> 2507 2508* {number} 2509 2510Readonly, This `outgoingMessage.writableLength` contains the number of 2511bytes (or objects) in the buffer ready to send. 2512 2513### `outgoingMessage.writableObjectMode` 2514<!-- YAML 2515added: v13.0.0 2516--> 2517 2518* {boolean} 2519 2520Readonly, always returns `false`. 2521 2522### `outgoingMessage.write(chunk[, encoding][, callback])` 2523<!-- YAML 2524added: v0.1.29 2525changes: 2526 - version: v0.11.6 2527 description: add `callback` argument. 2528--> 2529 2530* `chunk` {string | Buffer} 2531* `encoding` {string} **Default**: `utf-8` 2532* `callback` {Function} 2533* Returns {boolean} 2534 2535If this method is called and the header is not sent, it will call 2536`this._implicitHeader` to flush implicit header. 2537If the message should not have a body (indicated by `this._hasBody`), 2538the call is ignored and `chunk` will not be sent. It could be useful 2539when handling a particular message which must not include a body. 2540e.g. response to `HEAD` request, `204` and `304` response. 2541 2542`chunk` can be a string or a buffer. When `chunk` is a string, the 2543`encoding` parameter specifies how to encode `chunk` into a byte stream. 2544`callback` will be called when the `chunk` is flushed. 2545 2546If the message is transferred in chucked encoding 2547(indicated by `this.chunkedEncoding`), `chunk` will be flushed as 2548one chunk among a stream of chunks. Otherwise, it will be flushed as the 2549body of message. 2550 2551This method handles the raw body of the HTTP message and has nothing to do 2552with higher-level multi-part body encodings that may be used. 2553 2554If it is the first call to this method of a message, it will send the 2555buffered header first, then flush the `chunk` as described above. 2556 2557The second and successive calls to this method will assume the data 2558will be streamed and send the new data separately. It means that the response 2559is buffered up to the first chunk of the body. 2560 2561Returns `true` if the entire data was flushed successfully to the kernel 2562buffer. Returns `false` if all or part of the data was queued in the user 2563memory. Event `drain` will be emitted when the buffer is free again. 2564 2565## `http.METHODS` 2566<!-- YAML 2567added: v0.11.8 2568--> 2569 2570* {string[]} 2571 2572A list of the HTTP methods that are supported by the parser. 2573 2574## `http.STATUS_CODES` 2575<!-- YAML 2576added: v0.1.22 2577--> 2578 2579* {Object} 2580 2581A collection of all the standard HTTP response status codes, and the 2582short description of each. For example, `http.STATUS_CODES[404] === 'Not 2583Found'`. 2584 2585## `http.createServer([options][, requestListener])` 2586<!-- YAML 2587added: v0.1.13 2588changes: 2589 - version: 2590 - v13.8.0 2591 - v12.15.0 2592 - v10.19.0 2593 pr-url: https://github.com/nodejs/node/pull/31448 2594 description: The `insecureHTTPParser` option is supported now. 2595 - version: v13.3.0 2596 pr-url: https://github.com/nodejs/node/pull/30570 2597 description: The `maxHeaderSize` option is supported now. 2598 - version: 2599 - v9.6.0 2600 - v8.12.0 2601 pr-url: https://github.com/nodejs/node/pull/15752 2602 description: The `options` argument is supported now. 2603--> 2604 2605* `options` {Object} 2606 * `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` 2607 class to be used. Useful for extending the original `IncomingMessage`. 2608 **Default:** `IncomingMessage`. 2609 * `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class 2610 to be used. Useful for extending the original `ServerResponse`. **Default:** 2611 `ServerResponse`. 2612 * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts 2613 invalid HTTP headers when `true`. Using the insecure parser should be 2614 avoided. See [`--insecure-http-parser`][] for more information. 2615 **Default:** `false` 2616 * `maxHeaderSize` {number} Optionally overrides the value of 2617 [`--max-http-header-size`][] for requests received by this server, i.e. 2618 the maximum length of request headers in bytes. 2619 **Default:** 16384 (16KB). 2620* `requestListener` {Function} 2621 2622* Returns: {http.Server} 2623 2624Returns a new instance of [`http.Server`][]. 2625 2626The `requestListener` is a function which is automatically 2627added to the [`'request'`][] event. 2628 2629```cjs 2630const http = require('http'); 2631 2632// Create a local server to receive data from 2633const server = http.createServer((req, res) => { 2634 res.writeHead(200, { 'Content-Type': 'application/json' }); 2635 res.end(JSON.stringify({ 2636 data: 'Hello World!' 2637 })); 2638}); 2639 2640server.listen(8000); 2641``` 2642 2643```cjs 2644const http = require('http'); 2645 2646// Create a local server to receive data from 2647const server = http.createServer(); 2648 2649// Listen to the request event 2650server.on('request', (request, res) => { 2651 res.writeHead(200, { 'Content-Type': 'application/json' }); 2652 res.end(JSON.stringify({ 2653 data: 'Hello World!' 2654 })); 2655}); 2656 2657server.listen(8000); 2658``` 2659 2660## `http.get(options[, callback])` 2661## `http.get(url[, options][, callback])` 2662<!-- YAML 2663added: v0.3.6 2664changes: 2665 - version: v10.9.0 2666 pr-url: https://github.com/nodejs/node/pull/21616 2667 description: The `url` parameter can now be passed along with a separate 2668 `options` object. 2669 - version: v7.5.0 2670 pr-url: https://github.com/nodejs/node/pull/10638 2671 description: The `options` parameter can be a WHATWG `URL` object. 2672--> 2673 2674* `url` {string | URL} 2675* `options` {Object} Accepts the same `options` as 2676 [`http.request()`][], with the `method` always set to `GET`. 2677 Properties that are inherited from the prototype are ignored. 2678* `callback` {Function} 2679* Returns: {http.ClientRequest} 2680 2681Since most requests are GET requests without bodies, Node.js provides this 2682convenience method. The only difference between this method and 2683[`http.request()`][] is that it sets the method to GET and calls `req.end()` 2684automatically. The callback must take care to consume the response 2685data for reasons stated in [`http.ClientRequest`][] section. 2686 2687The `callback` is invoked with a single argument that is an instance of 2688[`http.IncomingMessage`][]. 2689 2690JSON fetching example: 2691 2692```js 2693http.get('http://localhost:8000/', (res) => { 2694 const { statusCode } = res; 2695 const contentType = res.headers['content-type']; 2696 2697 let error; 2698 // Any 2xx status code signals a successful response but 2699 // here we're only checking for 200. 2700 if (statusCode !== 200) { 2701 error = new Error('Request Failed.\n' + 2702 `Status Code: ${statusCode}`); 2703 } else if (!/^application\/json/.test(contentType)) { 2704 error = new Error('Invalid content-type.\n' + 2705 `Expected application/json but received ${contentType}`); 2706 } 2707 if (error) { 2708 console.error(error.message); 2709 // Consume response data to free up memory 2710 res.resume(); 2711 return; 2712 } 2713 2714 res.setEncoding('utf8'); 2715 let rawData = ''; 2716 res.on('data', (chunk) => { rawData += chunk; }); 2717 res.on('end', () => { 2718 try { 2719 const parsedData = JSON.parse(rawData); 2720 console.log(parsedData); 2721 } catch (e) { 2722 console.error(e.message); 2723 } 2724 }); 2725}).on('error', (e) => { 2726 console.error(`Got error: ${e.message}`); 2727}); 2728 2729// Create a local server to receive data from 2730const server = http.createServer((req, res) => { 2731 res.writeHead(200, { 'Content-Type': 'application/json' }); 2732 res.end(JSON.stringify({ 2733 data: 'Hello World!' 2734 })); 2735}); 2736 2737server.listen(8000); 2738``` 2739 2740## `http.globalAgent` 2741<!-- YAML 2742added: v0.5.9 2743--> 2744 2745* {http.Agent} 2746 2747Global instance of `Agent` which is used as the default for all HTTP client 2748requests. 2749 2750## `http.maxHeaderSize` 2751<!-- YAML 2752added: 2753 - v11.6.0 2754 - v10.15.0 2755--> 2756 2757* {number} 2758 2759Read-only property specifying the maximum allowed size of HTTP headers in bytes. 2760Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option. 2761 2762This can be overridden for servers and client requests by passing the 2763`maxHeaderSize` option. 2764 2765## `http.request(options[, callback])` 2766## `http.request(url[, options][, callback])` 2767<!-- YAML 2768added: v0.3.6 2769changes: 2770 - version: v14.18.0 2771 pr-url: https://github.com/nodejs/node/pull/39310 2772 description: When using a `URL` object parsed username and 2773 password will now be properly URI decoded. 2774 - version: v14.17.0 2775 pr-url: https://github.com/nodejs/node/pull/36048 2776 description: It is possible to abort a request with an AbortSignal. 2777 - version: 2778 - v13.8.0 2779 - v12.15.0 2780 - v10.19.0 2781 pr-url: https://github.com/nodejs/node/pull/31448 2782 description: The `insecureHTTPParser` option is supported now. 2783 - version: v13.3.0 2784 pr-url: https://github.com/nodejs/node/pull/30570 2785 description: The `maxHeaderSize` option is supported now. 2786 - version: v10.9.0 2787 pr-url: https://github.com/nodejs/node/pull/21616 2788 description: The `url` parameter can now be passed along with a separate 2789 `options` object. 2790 - version: v7.5.0 2791 pr-url: https://github.com/nodejs/node/pull/10638 2792 description: The `options` parameter can be a WHATWG `URL` object. 2793--> 2794 2795* `url` {string | URL} 2796* `options` {Object} 2797 * `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible 2798 values: 2799 * `undefined` (default): use [`http.globalAgent`][] for this host and port. 2800 * `Agent` object: explicitly use the passed in `Agent`. 2801 * `false`: causes a new `Agent` with default values to be used. 2802 * `auth` {string} Basic authentication i.e. `'user:password'` to compute an 2803 Authorization header. 2804 * `createConnection` {Function} A function that produces a socket/stream to 2805 use for the request when the `agent` option is not used. This can be used to 2806 avoid creating a custom `Agent` class just to override the default 2807 `createConnection` function. See [`agent.createConnection()`][] for more 2808 details. Any [`Duplex`][] stream is a valid return value. 2809 * `defaultPort` {number} Default port for the protocol. **Default:** 2810 `agent.defaultPort` if an `Agent` is used, else `undefined`. 2811 * `family` {number} IP address family to use when resolving `host` or 2812 `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and 2813 v6 will be used. 2814 * `headers` {Object} An object containing request headers. 2815 * `hints` {number} Optional [`dns.lookup()` hints][]. 2816 * `host` {string} A domain name or IP address of the server to issue the 2817 request to. **Default:** `'localhost'`. 2818 * `hostname` {string} Alias for `host`. To support [`url.parse()`][], 2819 `hostname` will be used if both `host` and `hostname` are specified. 2820 * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts 2821 invalid HTTP headers when `true`. Using the insecure parser should be 2822 avoided. See [`--insecure-http-parser`][] for more information. 2823 **Default:** `false` 2824 * `localAddress` {string} Local interface to bind for network connections. 2825 * `localPort` {number} Local port to connect from. 2826 * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][]. 2827 * `maxHeaderSize` {number} Optionally overrides the value of 2828 [`--max-http-header-size`][] for requests received from the server, i.e. 2829 the maximum length of response headers in bytes. 2830 **Default:** 16384 (16KB). 2831 * `method` {string} A string specifying the HTTP request method. **Default:** 2832 `'GET'`. 2833 * `path` {string} Request path. Should include query string if any. 2834 E.G. `'/index.html?page=12'`. An exception is thrown when the request path 2835 contains illegal characters. Currently, only spaces are rejected but that 2836 may change in the future. **Default:** `'/'`. 2837 * `port` {number} Port of remote server. **Default:** `defaultPort` if set, 2838 else `80`. 2839 * `protocol` {string} Protocol to use. **Default:** `'http:'`. 2840 * `setHost` {boolean}: Specifies whether or not to automatically add the 2841 `Host` header. Defaults to `true`. 2842 * `socketPath` {string} Unix Domain Socket (cannot be used if one of `host` 2843 or `port` is specified, those specify a TCP Socket). 2844 * `timeout` {number}: A number specifying the socket timeout in milliseconds. 2845 This will set the timeout before the socket is connected. 2846 * `signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing 2847 request. 2848* `callback` {Function} 2849* Returns: {http.ClientRequest} 2850 2851Node.js maintains several connections per server to make HTTP requests. 2852This function allows one to transparently issue requests. 2853 2854`url` can be a string or a [`URL`][] object. If `url` is a 2855string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][] 2856object, it will be automatically converted to an ordinary `options` object. 2857 2858If both `url` and `options` are specified, the objects are merged, with the 2859`options` properties taking precedence. 2860 2861The optional `callback` parameter will be added as a one-time listener for 2862the [`'response'`][] event. 2863 2864`http.request()` returns an instance of the [`http.ClientRequest`][] 2865class. The `ClientRequest` instance is a writable stream. If one needs to 2866upload a file with a POST request, then write to the `ClientRequest` object. 2867 2868```js 2869const http = require('http'); 2870 2871const postData = JSON.stringify({ 2872 'msg': 'Hello World!' 2873}); 2874 2875const options = { 2876 hostname: 'www.google.com', 2877 port: 80, 2878 path: '/upload', 2879 method: 'POST', 2880 headers: { 2881 'Content-Type': 'application/json', 2882 'Content-Length': Buffer.byteLength(postData) 2883 } 2884}; 2885 2886const req = http.request(options, (res) => { 2887 console.log(`STATUS: ${res.statusCode}`); 2888 console.log(`HEADERS: ${JSON.stringify(res.headers)}`); 2889 res.setEncoding('utf8'); 2890 res.on('data', (chunk) => { 2891 console.log(`BODY: ${chunk}`); 2892 }); 2893 res.on('end', () => { 2894 console.log('No more data in response.'); 2895 }); 2896}); 2897 2898req.on('error', (e) => { 2899 console.error(`problem with request: ${e.message}`); 2900}); 2901 2902// Write data to request body 2903req.write(postData); 2904req.end(); 2905``` 2906 2907In the example `req.end()` was called. With `http.request()` one 2908must always call `req.end()` to signify the end of the request - 2909even if there is no data being written to the request body. 2910 2911If any error is encountered during the request (be that with DNS resolution, 2912TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted 2913on the returned request object. As with all `'error'` events, if no listeners 2914are registered the error will be thrown. 2915 2916There are a few special headers that should be noted. 2917 2918* Sending a 'Connection: keep-alive' will notify Node.js that the connection to 2919 the server should be persisted until the next request. 2920 2921* Sending a 'Content-Length' header will disable the default chunked encoding. 2922 2923* Sending an 'Expect' header will immediately send the request headers. 2924 Usually, when sending 'Expect: 100-continue', both a timeout and a listener 2925 for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more 2926 information. 2927 2928* Sending an Authorization header will override using the `auth` option 2929 to compute basic authentication. 2930 2931Example using a [`URL`][] as `options`: 2932 2933```js 2934const options = new URL('http://abc:xyz@example.com'); 2935 2936const req = http.request(options, (res) => { 2937 // ... 2938}); 2939``` 2940 2941In a successful request, the following events will be emitted in the following 2942order: 2943 2944* `'socket'` 2945* `'response'` 2946 * `'data'` any number of times, on the `res` object 2947 (`'data'` will not be emitted at all if the response body is empty, for 2948 instance, in most redirects) 2949 * `'end'` on the `res` object 2950* `'close'` 2951 2952In the case of a connection error, the following events will be emitted: 2953 2954* `'socket'` 2955* `'error'` 2956* `'close'` 2957 2958In the case of a premature connection close before the response is received, 2959the following events will be emitted in the following order: 2960 2961* `'socket'` 2962* `'error'` with an error with message `'Error: socket hang up'` and code 2963 `'ECONNRESET'` 2964* `'close'` 2965 2966In the case of a premature connection close after the response is received, 2967the following events will be emitted in the following order: 2968 2969* `'socket'` 2970* `'response'` 2971 * `'data'` any number of times, on the `res` object 2972* (connection closed here) 2973* `'aborted'` on the `res` object 2974* `'close'` 2975* `'close'` on the `res` object 2976 2977If `req.destroy()` is called before a socket is assigned, the following 2978events will be emitted in the following order: 2979 2980* (`req.destroy()` called here) 2981* `'error'` with an error with message `'Error: socket hang up'` and code 2982 `'ECONNRESET'` 2983* `'close'` 2984 2985If `req.destroy()` is called before the connection succeeds, the following 2986events will be emitted in the following order: 2987 2988* `'socket'` 2989* (`req.destroy()` called here) 2990* `'error'` with an error with message `'Error: socket hang up'` and code 2991 `'ECONNRESET'` 2992* `'close'` 2993 2994If `req.destroy()` is called after the response is received, the following 2995events will be emitted in the following order: 2996 2997* `'socket'` 2998* `'response'` 2999 * `'data'` any number of times, on the `res` object 3000* (`req.destroy()` called here) 3001* `'aborted'` on the `res` object 3002* `'close'` 3003* `'close'` on the `res` object 3004 3005If `req.abort()` is called before a socket is assigned, the following 3006events will be emitted in the following order: 3007 3008* (`req.abort()` called here) 3009* `'abort'` 3010* `'close'` 3011 3012If `req.abort()` is called before the connection succeeds, the following 3013events will be emitted in the following order: 3014 3015* `'socket'` 3016* (`req.abort()` called here) 3017* `'abort'` 3018* `'error'` with an error with message `'Error: socket hang up'` and code 3019 `'ECONNRESET'` 3020* `'close'` 3021 3022If `req.abort()` is called after the response is received, the following 3023events will be emitted in the following order: 3024 3025* `'socket'` 3026* `'response'` 3027 * `'data'` any number of times, on the `res` object 3028* (`req.abort()` called here) 3029* `'abort'` 3030* `'aborted'` on the `res` object 3031* `'close'` 3032* `'close'` on the `res` object 3033 3034Setting the `timeout` option or using the `setTimeout()` function will 3035not abort the request or do anything besides add a `'timeout'` event. 3036 3037Passing an `AbortSignal` and then calling `abort` on the corresponding 3038`AbortController` will behave the same way as calling `.destroy()` on the 3039request itself. 3040 3041## `http.validateHeaderName(name)` 3042<!-- YAML 3043added: v14.3.0 3044--> 3045 3046* `name` {string} 3047 3048Performs the low-level validations on the provided `name` that are done when 3049`res.setHeader(name, value)` is called. 3050 3051Passing illegal value as `name` will result in a [`TypeError`][] being thrown, 3052identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. 3053 3054It is not necessary to use this method before passing headers to an HTTP request 3055or response. The HTTP module will automatically validate such headers. 3056Examples: 3057 3058Example: 3059```js 3060const { validateHeaderName } = require('http'); 3061 3062try { 3063 validateHeaderName(''); 3064} catch (err) { 3065 err instanceof TypeError; // --> true 3066 err.code; // --> 'ERR_INVALID_HTTP_TOKEN' 3067 err.message; // --> 'Header name must be a valid HTTP token [""]' 3068} 3069``` 3070 3071## `http.validateHeaderValue(name, value)` 3072<!-- YAML 3073added: v14.3.0 3074--> 3075 3076* `name` {string} 3077* `value` {any} 3078 3079Performs the low-level validations on the provided `value` that are done when 3080`res.setHeader(name, value)` is called. 3081 3082Passing illegal value as `value` will result in a [`TypeError`][] being thrown. 3083* Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. 3084* Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. 3085 3086It is not necessary to use this method before passing headers to an HTTP request 3087or response. The HTTP module will automatically validate such headers. 3088 3089Examples: 3090 3091```js 3092const { validateHeaderValue } = require('http'); 3093 3094try { 3095 validateHeaderValue('x-my-header', undefined); 3096} catch (err) { 3097 err instanceof TypeError; // --> true 3098 err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true 3099 err.message; // --> 'Invalid value "undefined" for header "x-my-header"' 3100} 3101 3102try { 3103 validateHeaderValue('x-my-header', 'oʊmɪɡə'); 3104} catch (err) { 3105 err instanceof TypeError; // --> true 3106 err.code === 'ERR_INVALID_CHAR'; // --> true 3107 err.message; // --> 'Invalid character in header content ["x-my-header"]' 3108} 3109``` 3110 3111[`'checkContinue'`]: #http_event_checkcontinue 3112[`'finish'`]: #http_event_finish 3113[`'request'`]: #http_event_request 3114[`'response'`]: #http_event_response 3115[`'upgrade'`]: #http_event_upgrade 3116[`--insecure-http-parser`]: cli.md#cli_insecure_http_parser 3117[`--max-http-header-size`]: cli.md#cli_max_http_header_size_size 3118[`Agent`]: #http_class_http_agent 3119[`Buffer.byteLength()`]: buffer.md#buffer_static_method_buffer_bytelength_string_encoding 3120[`Duplex`]: stream.md#stream_class_stream_duplex 3121[`HPE_HEADER_OVERFLOW`]: errors.md#errors_hpe_header_overflow 3122[`TypeError`]: errors.md#errors_class_typeerror 3123[`URL`]: url.md#url_the_whatwg_url_api 3124[`agent.createConnection()`]: #http_agent_createconnection_options_callback 3125[`agent.getName()`]: #http_agent_getname_options 3126[`destroy()`]: #http_agent_destroy 3127[`dns.lookup()`]: dns.md#dns_dns_lookup_hostname_options_callback 3128[`dns.lookup()` hints]: dns.md#dns_supported_getaddrinfo_flags 3129[`getHeader(name)`]: #http_request_getheader_name 3130[`http.Agent`]: #http_class_http_agent 3131[`http.ClientRequest`]: #http_class_http_clientrequest 3132[`http.IncomingMessage`]: #http_class_http_incomingmessage 3133[`http.ServerResponse`]: #http_class_http_serverresponse 3134[`http.Server`]: #http_class_http_server 3135[`http.get()`]: #http_http_get_options_callback 3136[`http.globalAgent`]: #http_http_globalagent 3137[`http.request()`]: #http_http_request_options_callback 3138[`message.headers`]: #http_message_headers 3139[`net.Server.close()`]: net.md#net_server_close_callback 3140[`net.Server`]: net.md#net_class_net_server 3141[`net.Socket`]: net.md#net_class_net_socket 3142[`net.createConnection()`]: net.md#net_net_createconnection_options_connectlistener 3143[`new URL()`]: url.md#url_new_url_input_base 3144[`outgoingMessage.socket`]: #http_outgoingmessage_socket 3145[`removeHeader(name)`]: #http_request_removeheader_name 3146[`request.destroy()`]: #http_request_destroy_error 3147[`request.end()`]: #http_request_end_data_encoding_callback 3148[`request.flushHeaders()`]: #http_request_flushheaders 3149[`request.getHeader()`]: #http_request_getheader_name 3150[`request.setHeader()`]: #http_request_setheader_name_value 3151[`request.setTimeout()`]: #http_request_settimeout_timeout_callback 3152[`request.socket.getPeerCertificate()`]: tls.md#tls_tlssocket_getpeercertificate_detailed 3153[`request.socket`]: #http_request_socket 3154[`request.writableEnded`]: #http_request_writableended 3155[`request.writableFinished`]: #http_request_writablefinished 3156[`request.write(data, encoding)`]: #http_request_write_chunk_encoding_callback 3157[`response.end()`]: #http_response_end_data_encoding_callback 3158[`response.getHeader()`]: #http_response_getheader_name 3159[`response.setHeader()`]: #http_response_setheader_name_value 3160[`response.socket`]: #http_response_socket 3161[`response.writableEnded`]: #http_response_writableended 3162[`response.writableFinished`]: #http_response_writablefinished 3163[`response.write()`]: #http_response_write_chunk_encoding_callback 3164[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback 3165[`response.writeContinue()`]: #http_response_writecontinue 3166[`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers 3167[`server.listen()`]: net.md#net_server_listen 3168[`server.timeout`]: #http_server_timeout 3169[`setHeader(name, value)`]: #http_request_setheader_name_value 3170[`socket.connect()`]: net.md#net_socket_connect_options_connectlistener 3171[`socket.setKeepAlive()`]: net.md#net_socket_setkeepalive_enable_initialdelay 3172[`socket.setNoDelay()`]: net.md#net_socket_setnodelay_nodelay 3173[`socket.setTimeout()`]: net.md#net_socket_settimeout_timeout_callback 3174[`socket.unref()`]: net.md#net_socket_unref 3175[`url.parse()`]: url.md#url_url_parse_urlstring_parsequerystring_slashesdenotehost 3176[`writable.cork()`]: stream.md#stream_writable_cork 3177[`writable.destroy()`]: stream.md#stream_writable_destroy_error 3178[`writable.destroyed`]: stream.md#stream_writable_destroyed 3179[`writable.uncork()`]: stream.md#stream_writable_uncork 3180