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('node: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 21```js 22{ 'content-length': '123', 23 'content-type': 'text/plain', 24 'connection': 'keep-alive', 25 'host': 'example.com', 26 'accept': '*/*' } 27``` 28 29Keys are lowercased. Values are not modified. 30 31In order to support the full spectrum of possible HTTP applications, the Node.js 32HTTP API is very low-level. It deals with stream handling and message 33parsing only. It parses a message into headers and body but it does not 34parse the actual headers or the body. 35 36See [`message.headers`][] for details on how duplicate headers are handled. 37 38The raw headers as they were received are retained in the `rawHeaders` 39property, which is an array of `[key, value, key2, value2, ...]`. For 40example, the previous message header object might have a `rawHeaders` 41list like the following: 42 43<!-- eslint-disable semi --> 44 45```js 46[ 'ConTent-Length', '123456', 47 'content-LENGTH', '123', 48 'content-type', 'text/plain', 49 'CONNECTION', 'keep-alive', 50 'Host', 'example.com', 51 'accepT', '*/*' ] 52``` 53 54## Class: `http.Agent` 55 56<!-- YAML 57added: v0.3.4 58--> 59 60An `Agent` is responsible for managing connection persistence 61and reuse for HTTP clients. It maintains a queue of pending requests 62for a given host and port, reusing a single socket connection for each 63until the queue is empty, at which time the socket is either destroyed 64or put into a pool where it is kept to be used again for requests to the 65same host and port. Whether it is destroyed or pooled depends on the 66`keepAlive` [option](#new-agentoptions). 67 68Pooled connections have TCP Keep-Alive enabled for them, but servers may 69still close idle connections, in which case they will be removed from the 70pool and a new connection will be made when a new HTTP request is made for 71that host and port. Servers may also refuse to allow multiple requests 72over the same connection, in which case the connection will have to be 73remade for every request and cannot be pooled. The `Agent` will still make 74the requests to that server, but each one will occur over a new connection. 75 76When a connection is closed by the client or the server, it is removed 77from the pool. Any unused sockets in the pool will be unrefed so as not 78to keep the Node.js process running when there are no outstanding requests. 79(see [`socket.unref()`][]). 80 81It is good practice, to [`destroy()`][] an `Agent` instance when it is no 82longer in use, because unused sockets consume OS resources. 83 84Sockets are removed from an agent when the socket emits either 85a `'close'` event or an `'agentRemove'` event. When intending to keep one 86HTTP request open for a long time without keeping it in the agent, something 87like the following may be done: 88 89```js 90http.get(options, (res) => { 91 // Do stuff 92}).on('socket', (socket) => { 93 socket.emit('agentRemove'); 94}); 95``` 96 97An agent may also be used for an individual request. By providing 98`{agent: false}` as an option to the `http.get()` or `http.request()` 99functions, a one-time use `Agent` with default options will be used 100for the client connection. 101 102`agent:false`: 103 104```js 105http.get({ 106 hostname: 'localhost', 107 port: 80, 108 path: '/', 109 agent: false, // Create a new agent just for this one request 110}, (res) => { 111 // Do stuff with response 112}); 113``` 114 115### `new Agent([options])` 116 117<!-- YAML 118added: v0.3.4 119changes: 120 - version: 121 - v15.6.0 122 - v14.17.0 123 pr-url: https://github.com/nodejs/node/pull/36685 124 description: Change the default scheduling from 'fifo' to 'lifo'. 125 - version: 126 - v14.5.0 127 - v12.19.0 128 pr-url: https://github.com/nodejs/node/pull/33617 129 description: Add `maxTotalSockets` option to agent constructor. 130 - version: 131 - v14.5.0 132 - v12.20.0 133 pr-url: https://github.com/nodejs/node/pull/33278 134 description: Add `scheduling` option to specify the free socket 135 scheduling strategy. 136--> 137 138* `options` {Object} Set of configurable options to set on the agent. 139 Can have the following fields: 140 * `keepAlive` {boolean} Keep sockets around even when there are no 141 outstanding requests, so they can be used for future requests without 142 having to reestablish a TCP connection. Not to be confused with the 143 `keep-alive` value of the `Connection` header. The `Connection: keep-alive` 144 header is always sent when using an agent except when the `Connection` 145 header is explicitly specified or when the `keepAlive` and `maxSockets` 146 options are respectively set to `false` and `Infinity`, in which case 147 `Connection: close` will be used. **Default:** `false`. 148 * `keepAliveMsecs` {number} When using the `keepAlive` option, specifies 149 the [initial delay][] 150 for TCP Keep-Alive packets. Ignored when the 151 `keepAlive` option is `false` or `undefined`. **Default:** `1000`. 152 * `maxSockets` {number} Maximum number of sockets to allow per host. 153 If the same host opens multiple concurrent connections, each request 154 will use new socket until the `maxSockets` value is reached. 155 If the host attempts to open more connections than `maxSockets`, 156 the additional requests will enter into a pending request queue, and 157 will enter active connection state when an existing connection terminates. 158 This makes sure there are at most `maxSockets` active connections at 159 any point in time, from a given host. 160 **Default:** `Infinity`. 161 * `maxTotalSockets` {number} Maximum number of sockets allowed for 162 all hosts in total. Each request will use a new socket 163 until the maximum is reached. 164 **Default:** `Infinity`. 165 * `maxFreeSockets` {number} Maximum number of sockets per host to leave open 166 in a free state. Only relevant if `keepAlive` is set to `true`. 167 **Default:** `256`. 168 * `scheduling` {string} Scheduling strategy to apply when picking 169 the next free socket to use. It can be `'fifo'` or `'lifo'`. 170 The main difference between the two scheduling strategies is that `'lifo'` 171 selects the most recently used socket, while `'fifo'` selects 172 the least recently used socket. 173 In case of a low rate of request per second, the `'lifo'` scheduling 174 will lower the risk of picking a socket that might have been closed 175 by the server due to inactivity. 176 In case of a high rate of request per second, 177 the `'fifo'` scheduling will maximize the number of open sockets, 178 while the `'lifo'` scheduling will keep it as low as possible. 179 **Default:** `'lifo'`. 180 * `timeout` {number} Socket timeout in milliseconds. 181 This will set the timeout when the socket is created. 182 183`options` in [`socket.connect()`][] are also supported. 184 185The default [`http.globalAgent`][] that is used by [`http.request()`][] has all 186of these values set to their respective defaults. 187 188To configure any of them, a custom [`http.Agent`][] instance must be created. 189 190```mjs 191import { Agent, request } from 'node:http'; 192const keepAliveAgent = new Agent({ keepAlive: true }); 193options.agent = keepAliveAgent; 194request(options, onResponseCallback); 195``` 196 197```cjs 198const http = require('node:http'); 199const keepAliveAgent = new http.Agent({ keepAlive: true }); 200options.agent = keepAliveAgent; 201http.request(options, onResponseCallback); 202``` 203 204### `agent.createConnection(options[, callback])` 205 206<!-- YAML 207added: v0.11.4 208--> 209 210* `options` {Object} Options containing connection details. Check 211 [`net.createConnection()`][] for the format of the options 212* `callback` {Function} Callback function that receives the created socket 213* Returns: {stream.Duplex} 214 215Produces a socket/stream to be used for HTTP requests. 216 217By default, this function is the same as [`net.createConnection()`][]. However, 218custom agents may override this method in case greater flexibility is desired. 219 220A socket/stream can be supplied in one of two ways: by returning the 221socket/stream from this function, or by passing the socket/stream to `callback`. 222 223This method is guaranteed to return an instance of the {net.Socket} class, 224a subclass of {stream.Duplex}, unless the user specifies a socket 225type other than {net.Socket}. 226 227`callback` has a signature of `(err, stream)`. 228 229### `agent.keepSocketAlive(socket)` 230 231<!-- YAML 232added: v8.1.0 233--> 234 235* `socket` {stream.Duplex} 236 237Called when `socket` is detached from a request and could be persisted by the 238`Agent`. Default behavior is to: 239 240```js 241socket.setKeepAlive(true, this.keepAliveMsecs); 242socket.unref(); 243return true; 244``` 245 246This method can be overridden by a particular `Agent` subclass. If this 247method returns a falsy value, the socket will be destroyed instead of persisting 248it for use with the next request. 249 250The `socket` argument can be an instance of {net.Socket}, a subclass of 251{stream.Duplex}. 252 253### `agent.reuseSocket(socket, request)` 254 255<!-- YAML 256added: v8.1.0 257--> 258 259* `socket` {stream.Duplex} 260* `request` {http.ClientRequest} 261 262Called when `socket` is attached to `request` after being persisted because of 263the keep-alive options. Default behavior is to: 264 265```js 266socket.ref(); 267``` 268 269This method can be overridden by a particular `Agent` subclass. 270 271The `socket` argument can be an instance of {net.Socket}, a subclass of 272{stream.Duplex}. 273 274### `agent.destroy()` 275 276<!-- YAML 277added: v0.11.4 278--> 279 280Destroy any sockets that are currently in use by the agent. 281 282It is usually not necessary to do this. However, if using an 283agent with `keepAlive` enabled, then it is best to explicitly shut down 284the agent when it is no longer needed. Otherwise, 285sockets might stay open for quite a long time before the server 286terminates them. 287 288### `agent.freeSockets` 289 290<!-- YAML 291added: v0.11.4 292changes: 293 - version: v16.0.0 294 pr-url: https://github.com/nodejs/node/pull/36409 295 description: The property now has a `null` prototype. 296--> 297 298* {Object} 299 300An object which contains arrays of sockets currently awaiting use by 301the agent when `keepAlive` is enabled. Do not modify. 302 303Sockets in the `freeSockets` list will be automatically destroyed and 304removed from the array on `'timeout'`. 305 306### `agent.getName([options])` 307 308<!-- YAML 309added: v0.11.4 310changes: 311 - version: v17.7.0 312 pr-url: https://github.com/nodejs/node/pull/41906 313 description: The `options` parameter is now optional. 314--> 315 316* `options` {Object} A set of options providing information for name generation 317 * `host` {string} A domain name or IP address of the server to issue the 318 request to 319 * `port` {number} Port of remote server 320 * `localAddress` {string} Local interface to bind for network connections 321 when issuing the request 322 * `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`. 323* Returns: {string} 324 325Get a unique name for a set of request options, to determine whether a 326connection can be reused. For an HTTP agent, this returns 327`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, 328the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options 329that determine socket reusability. 330 331### `agent.maxFreeSockets` 332 333<!-- YAML 334added: v0.11.7 335--> 336 337* {number} 338 339By default set to 256. For agents with `keepAlive` enabled, this 340sets the maximum number of sockets that will be left open in the free 341state. 342 343### `agent.maxSockets` 344 345<!-- YAML 346added: v0.3.6 347--> 348 349* {number} 350 351By default set to `Infinity`. Determines how many concurrent sockets the agent 352can have open per origin. Origin is the returned value of [`agent.getName()`][]. 353 354### `agent.maxTotalSockets` 355 356<!-- YAML 357added: 358 - v14.5.0 359 - v12.19.0 360--> 361 362* {number} 363 364By default set to `Infinity`. Determines how many concurrent sockets the agent 365can have open. Unlike `maxSockets`, this parameter applies across all origins. 366 367### `agent.requests` 368 369<!-- YAML 370added: v0.5.9 371changes: 372 - version: v16.0.0 373 pr-url: https://github.com/nodejs/node/pull/36409 374 description: The property now has a `null` prototype. 375--> 376 377* {Object} 378 379An object which contains queues of requests that have not yet been assigned to 380sockets. Do not modify. 381 382### `agent.sockets` 383 384<!-- YAML 385added: v0.3.6 386changes: 387 - version: v16.0.0 388 pr-url: https://github.com/nodejs/node/pull/36409 389 description: The property now has a `null` prototype. 390--> 391 392* {Object} 393 394An object which contains arrays of sockets currently in use by the 395agent. Do not modify. 396 397## Class: `http.ClientRequest` 398 399<!-- YAML 400added: v0.1.17 401--> 402 403* Extends: {http.OutgoingMessage} 404 405This object is created internally and returned from [`http.request()`][]. It 406represents an _in-progress_ request whose header has already been queued. The 407header is still mutable using the [`setHeader(name, value)`][], 408[`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will 409be sent along with the first data chunk or when calling [`request.end()`][]. 410 411To get the response, add a listener for [`'response'`][] to the request object. 412[`'response'`][] will be emitted from the request object when the response 413headers have been received. The [`'response'`][] event is executed with one 414argument which is an instance of [`http.IncomingMessage`][]. 415 416During the [`'response'`][] event, one can add listeners to the 417response object; particularly to listen for the `'data'` event. 418 419If no [`'response'`][] handler is added, then the response will be 420entirely discarded. However, if a [`'response'`][] event handler is added, 421then the data from the response object **must** be consumed, either by 422calling `response.read()` whenever there is a `'readable'` event, or 423by adding a `'data'` handler, or by calling the `.resume()` method. 424Until the data is consumed, the `'end'` event will not fire. Also, until 425the data is read it will consume memory that can eventually lead to a 426'process out of memory' error. 427 428For backward compatibility, `res` will only emit `'error'` if there is an 429`'error'` listener registered. 430 431Set `Content-Length` header to limit the response body size. 432If [`response.strictContentLength`][] is set to `true`, mismatching the 433`Content-Length` header value will result in an `Error` being thrown, 434identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][]. 435 436`Content-Length` value should be in bytes, not characters. Use 437[`Buffer.byteLength()`][] to determine the length of the body in bytes. 438 439### Event: `'abort'` 440 441<!-- YAML 442added: v1.4.1 443deprecated: 444 - v17.0.0 445 - v16.12.0 446--> 447 448> Stability: 0 - Deprecated. Listen for the `'close'` event instead. 449 450Emitted when the request has been aborted by the client. This event is only 451emitted on the first call to `abort()`. 452 453### Event: `'close'` 454 455<!-- YAML 456added: v0.5.4 457--> 458 459Indicates that the request is completed, or its underlying connection was 460terminated prematurely (before the response completion). 461 462### Event: `'connect'` 463 464<!-- YAML 465added: v0.7.0 466--> 467 468* `response` {http.IncomingMessage} 469* `socket` {stream.Duplex} 470* `head` {Buffer} 471 472Emitted each time a server responds to a request with a `CONNECT` method. If 473this event is not being listened for, clients receiving a `CONNECT` method will 474have their connections closed. 475 476This event is guaranteed to be passed an instance of the {net.Socket} class, 477a subclass of {stream.Duplex}, unless the user specifies a socket 478type other than {net.Socket}. 479 480A client and server pair demonstrating how to listen for the `'connect'` event: 481 482```mjs 483import { createServer, request } from 'node:http'; 484import { connect } from 'node:net'; 485import { URL } from 'node:url'; 486 487// Create an HTTP tunneling proxy 488const proxy = createServer((req, res) => { 489 res.writeHead(200, { 'Content-Type': 'text/plain' }); 490 res.end('okay'); 491}); 492proxy.on('connect', (req, clientSocket, head) => { 493 // Connect to an origin server 494 const { port, hostname } = new URL(`http://${req.url}`); 495 const serverSocket = connect(port || 80, hostname, () => { 496 clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 497 'Proxy-agent: Node.js-Proxy\r\n' + 498 '\r\n'); 499 serverSocket.write(head); 500 serverSocket.pipe(clientSocket); 501 clientSocket.pipe(serverSocket); 502 }); 503}); 504 505// Now that proxy is running 506proxy.listen(1337, '127.0.0.1', () => { 507 508 // Make a request to a tunneling proxy 509 const options = { 510 port: 1337, 511 host: '127.0.0.1', 512 method: 'CONNECT', 513 path: 'www.google.com:80', 514 }; 515 516 const req = request(options); 517 req.end(); 518 519 req.on('connect', (res, socket, head) => { 520 console.log('got connected!'); 521 522 // Make a request over an HTTP tunnel 523 socket.write('GET / HTTP/1.1\r\n' + 524 'Host: www.google.com:80\r\n' + 525 'Connection: close\r\n' + 526 '\r\n'); 527 socket.on('data', (chunk) => { 528 console.log(chunk.toString()); 529 }); 530 socket.on('end', () => { 531 proxy.close(); 532 }); 533 }); 534}); 535``` 536 537```cjs 538const http = require('node:http'); 539const net = require('node:net'); 540const { URL } = require('node:url'); 541 542// Create an HTTP tunneling proxy 543const proxy = http.createServer((req, res) => { 544 res.writeHead(200, { 'Content-Type': 'text/plain' }); 545 res.end('okay'); 546}); 547proxy.on('connect', (req, clientSocket, head) => { 548 // Connect to an origin server 549 const { port, hostname } = new URL(`http://${req.url}`); 550 const serverSocket = net.connect(port || 80, hostname, () => { 551 clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 552 'Proxy-agent: Node.js-Proxy\r\n' + 553 '\r\n'); 554 serverSocket.write(head); 555 serverSocket.pipe(clientSocket); 556 clientSocket.pipe(serverSocket); 557 }); 558}); 559 560// Now that proxy is running 561proxy.listen(1337, '127.0.0.1', () => { 562 563 // Make a request to a tunneling proxy 564 const options = { 565 port: 1337, 566 host: '127.0.0.1', 567 method: 'CONNECT', 568 path: 'www.google.com:80', 569 }; 570 571 const req = http.request(options); 572 req.end(); 573 574 req.on('connect', (res, socket, head) => { 575 console.log('got connected!'); 576 577 // Make a request over an HTTP tunnel 578 socket.write('GET / HTTP/1.1\r\n' + 579 'Host: www.google.com:80\r\n' + 580 'Connection: close\r\n' + 581 '\r\n'); 582 socket.on('data', (chunk) => { 583 console.log(chunk.toString()); 584 }); 585 socket.on('end', () => { 586 proxy.close(); 587 }); 588 }); 589}); 590``` 591 592### Event: `'continue'` 593 594<!-- YAML 595added: v0.3.2 596--> 597 598Emitted when the server sends a '100 Continue' HTTP response, usually because 599the request contained 'Expect: 100-continue'. This is an instruction that 600the client should send the request body. 601 602### Event: `'finish'` 603 604<!-- YAML 605added: v0.3.6 606--> 607 608Emitted when the request has been sent. More specifically, this event is emitted 609when the last segment of the response headers and body have been handed off to 610the operating system for transmission over the network. It does not imply that 611the server has received anything yet. 612 613### Event: `'information'` 614 615<!-- YAML 616added: v10.0.0 617--> 618 619* `info` {Object} 620 * `httpVersion` {string} 621 * `httpVersionMajor` {integer} 622 * `httpVersionMinor` {integer} 623 * `statusCode` {integer} 624 * `statusMessage` {string} 625 * `headers` {Object} 626 * `rawHeaders` {string\[]} 627 628Emitted when the server sends a 1xx intermediate response (excluding 101 629Upgrade). The listeners of this event will receive an object containing the 630HTTP version, status code, status message, key-value headers object, 631and array with the raw header names followed by their respective values. 632 633```mjs 634import { request } from 'node:http'; 635 636const options = { 637 host: '127.0.0.1', 638 port: 8080, 639 path: '/length_request', 640}; 641 642// Make a request 643const req = request(options); 644req.end(); 645 646req.on('information', (info) => { 647 console.log(`Got information prior to main response: ${info.statusCode}`); 648}); 649``` 650 651```cjs 652const http = require('node:http'); 653 654const options = { 655 host: '127.0.0.1', 656 port: 8080, 657 path: '/length_request', 658}; 659 660// Make a request 661const req = http.request(options); 662req.end(); 663 664req.on('information', (info) => { 665 console.log(`Got information prior to main response: ${info.statusCode}`); 666}); 667``` 668 669101 Upgrade statuses do not fire this event due to their break from the 670traditional HTTP request/response chain, such as web sockets, in-place TLS 671upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the 672[`'upgrade'`][] event instead. 673 674### Event: `'response'` 675 676<!-- YAML 677added: v0.1.0 678--> 679 680* `response` {http.IncomingMessage} 681 682Emitted when a response is received to this request. This event is emitted only 683once. 684 685### Event: `'socket'` 686 687<!-- YAML 688added: v0.5.3 689--> 690 691* `socket` {stream.Duplex} 692 693This event is guaranteed to be passed an instance of the {net.Socket} class, 694a subclass of {stream.Duplex}, unless the user specifies a socket 695type other than {net.Socket}. 696 697### Event: `'timeout'` 698 699<!-- YAML 700added: v0.7.8 701--> 702 703Emitted when the underlying socket times out from inactivity. This only notifies 704that the socket has been idle. The request must be destroyed manually. 705 706See also: [`request.setTimeout()`][]. 707 708### Event: `'upgrade'` 709 710<!-- YAML 711added: v0.1.94 712--> 713 714* `response` {http.IncomingMessage} 715* `socket` {stream.Duplex} 716* `head` {Buffer} 717 718Emitted each time a server responds to a request with an upgrade. If this 719event is not being listened for and the response status code is 101 Switching 720Protocols, clients receiving an upgrade header will have their connections 721closed. 722 723This event is guaranteed to be passed an instance of the {net.Socket} class, 724a subclass of {stream.Duplex}, unless the user specifies a socket 725type other than {net.Socket}. 726 727A client server pair demonstrating how to listen for the `'upgrade'` event. 728 729```mjs 730import http from 'node:http'; 731import process from 'node:process'; 732 733// Create an HTTP server 734const server = http.createServer((req, res) => { 735 res.writeHead(200, { 'Content-Type': 'text/plain' }); 736 res.end('okay'); 737}); 738server.on('upgrade', (req, socket, head) => { 739 socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 740 'Upgrade: WebSocket\r\n' + 741 'Connection: Upgrade\r\n' + 742 '\r\n'); 743 744 socket.pipe(socket); // echo back 745}); 746 747// Now that server is running 748server.listen(1337, '127.0.0.1', () => { 749 750 // make a request 751 const options = { 752 port: 1337, 753 host: '127.0.0.1', 754 headers: { 755 'Connection': 'Upgrade', 756 'Upgrade': 'websocket', 757 }, 758 }; 759 760 const req = http.request(options); 761 req.end(); 762 763 req.on('upgrade', (res, socket, upgradeHead) => { 764 console.log('got upgraded!'); 765 socket.end(); 766 process.exit(0); 767 }); 768}); 769``` 770 771```cjs 772const http = require('node:http'); 773 774// Create an HTTP server 775const server = http.createServer((req, res) => { 776 res.writeHead(200, { 'Content-Type': 'text/plain' }); 777 res.end('okay'); 778}); 779server.on('upgrade', (req, socket, head) => { 780 socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 781 'Upgrade: WebSocket\r\n' + 782 'Connection: Upgrade\r\n' + 783 '\r\n'); 784 785 socket.pipe(socket); // echo back 786}); 787 788// Now that server is running 789server.listen(1337, '127.0.0.1', () => { 790 791 // make a request 792 const options = { 793 port: 1337, 794 host: '127.0.0.1', 795 headers: { 796 'Connection': 'Upgrade', 797 'Upgrade': 'websocket', 798 }, 799 }; 800 801 const req = http.request(options); 802 req.end(); 803 804 req.on('upgrade', (res, socket, upgradeHead) => { 805 console.log('got upgraded!'); 806 socket.end(); 807 process.exit(0); 808 }); 809}); 810``` 811 812### `request.abort()` 813 814<!-- YAML 815added: v0.3.8 816deprecated: 817 - v14.1.0 818 - v13.14.0 819--> 820 821> Stability: 0 - Deprecated: Use [`request.destroy()`][] instead. 822 823Marks the request as aborting. Calling this will cause remaining data 824in the response to be dropped and the socket to be destroyed. 825 826### `request.aborted` 827 828<!-- YAML 829added: v0.11.14 830deprecated: 831 - v17.0.0 832 - v16.12.0 833changes: 834 - version: v11.0.0 835 pr-url: https://github.com/nodejs/node/pull/20230 836 description: The `aborted` property is no longer a timestamp number. 837--> 838 839> Stability: 0 - Deprecated. Check [`request.destroyed`][] instead. 840 841* {boolean} 842 843The `request.aborted` property will be `true` if the request has 844been aborted. 845 846### `request.connection` 847 848<!-- YAML 849added: v0.3.0 850deprecated: v13.0.0 851--> 852 853> Stability: 0 - Deprecated. Use [`request.socket`][]. 854 855* {stream.Duplex} 856 857See [`request.socket`][]. 858 859### `request.cork()` 860 861<!-- YAML 862added: 863 - v13.2.0 864 - v12.16.0 865--> 866 867See [`writable.cork()`][]. 868 869### `request.end([data[, encoding]][, callback])` 870 871<!-- YAML 872added: v0.1.90 873changes: 874 - version: v15.0.0 875 pr-url: https://github.com/nodejs/node/pull/33155 876 description: The `data` parameter can now be a `Uint8Array`. 877 - version: v10.0.0 878 pr-url: https://github.com/nodejs/node/pull/18780 879 description: This method now returns a reference to `ClientRequest`. 880--> 881 882* `data` {string|Buffer|Uint8Array} 883* `encoding` {string} 884* `callback` {Function} 885* Returns: {this} 886 887Finishes sending the request. If any parts of the body are 888unsent, it will flush them to the stream. If the request is 889chunked, this will send the terminating `'0\r\n\r\n'`. 890 891If `data` is specified, it is equivalent to calling 892[`request.write(data, encoding)`][] followed by `request.end(callback)`. 893 894If `callback` is specified, it will be called when the request stream 895is finished. 896 897### `request.destroy([error])` 898 899<!-- YAML 900added: v0.3.0 901changes: 902 - version: v14.5.0 903 pr-url: https://github.com/nodejs/node/pull/32789 904 description: The function returns `this` for consistency with other Readable 905 streams. 906--> 907 908* `error` {Error} Optional, an error to emit with `'error'` event. 909* Returns: {this} 910 911Destroy the request. Optionally emit an `'error'` event, 912and emit a `'close'` event. Calling this will cause remaining data 913in the response to be dropped and the socket to be destroyed. 914 915See [`writable.destroy()`][] for further details. 916 917#### `request.destroyed` 918 919<!-- YAML 920added: 921 - v14.1.0 922 - v13.14.0 923--> 924 925* {boolean} 926 927Is `true` after [`request.destroy()`][] has been called. 928 929See [`writable.destroyed`][] for further details. 930 931### `request.finished` 932 933<!-- YAML 934added: v0.0.1 935deprecated: 936 - v13.4.0 937 - v12.16.0 938--> 939 940> Stability: 0 - Deprecated. Use [`request.writableEnded`][]. 941 942* {boolean} 943 944The `request.finished` property will be `true` if [`request.end()`][] 945has been called. `request.end()` will automatically be called if the 946request was initiated via [`http.get()`][]. 947 948### `request.flushHeaders()` 949 950<!-- YAML 951added: v1.6.0 952--> 953 954Flushes the request headers. 955 956For efficiency reasons, Node.js normally buffers the request headers until 957`request.end()` is called or the first chunk of request data is written. It 958then tries to pack the request headers and data into a single TCP packet. 959 960That's usually desired (it saves a TCP round-trip), but not when the first 961data is not sent until possibly much later. `request.flushHeaders()` bypasses 962the optimization and kickstarts the request. 963 964### `request.getHeader(name)` 965 966<!-- YAML 967added: v1.6.0 968--> 969 970* `name` {string} 971* Returns: {any} 972 973Reads out a header on the request. The name is case-insensitive. 974The type of the return value depends on the arguments provided to 975[`request.setHeader()`][]. 976 977```js 978request.setHeader('content-type', 'text/html'); 979request.setHeader('Content-Length', Buffer.byteLength(body)); 980request.setHeader('Cookie', ['type=ninja', 'language=javascript']); 981const contentType = request.getHeader('Content-Type'); 982// 'contentType' is 'text/html' 983const contentLength = request.getHeader('Content-Length'); 984// 'contentLength' is of type number 985const cookie = request.getHeader('Cookie'); 986// 'cookie' is of type string[] 987``` 988 989### `request.getHeaderNames()` 990 991<!-- YAML 992added: v7.7.0 993--> 994 995* Returns: {string\[]} 996 997Returns an array containing the unique names of the current outgoing headers. 998All header names are lowercase. 999 1000```js 1001request.setHeader('Foo', 'bar'); 1002request.setHeader('Cookie', ['foo=bar', 'bar=baz']); 1003 1004const headerNames = request.getHeaderNames(); 1005// headerNames === ['foo', 'cookie'] 1006``` 1007 1008### `request.getHeaders()` 1009 1010<!-- YAML 1011added: v7.7.0 1012--> 1013 1014* Returns: {Object} 1015 1016Returns a shallow copy of the current outgoing headers. Since a shallow copy 1017is used, array values may be mutated without additional calls to various 1018header-related http module methods. The keys of the returned object are the 1019header names and the values are the respective header values. All header names 1020are lowercase. 1021 1022The object returned by the `request.getHeaders()` method _does not_ 1023prototypically inherit from the JavaScript `Object`. This means that typical 1024`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others 1025are not defined and _will not work_. 1026 1027```js 1028request.setHeader('Foo', 'bar'); 1029request.setHeader('Cookie', ['foo=bar', 'bar=baz']); 1030 1031const headers = request.getHeaders(); 1032// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] } 1033``` 1034 1035### `request.getRawHeaderNames()` 1036 1037<!-- YAML 1038added: 1039 - v15.13.0 1040 - v14.17.0 1041--> 1042 1043* Returns: {string\[]} 1044 1045Returns an array containing the unique names of the current outgoing raw 1046headers. Header names are returned with their exact casing being set. 1047 1048```js 1049request.setHeader('Foo', 'bar'); 1050request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 1051 1052const headerNames = request.getRawHeaderNames(); 1053// headerNames === ['Foo', 'Set-Cookie'] 1054``` 1055 1056### `request.hasHeader(name)` 1057 1058<!-- YAML 1059added: v7.7.0 1060--> 1061 1062* `name` {string} 1063* Returns: {boolean} 1064 1065Returns `true` if the header identified by `name` is currently set in the 1066outgoing headers. The header name matching is case-insensitive. 1067 1068```js 1069const hasContentType = request.hasHeader('content-type'); 1070``` 1071 1072### `request.maxHeadersCount` 1073 1074* {number} **Default:** `2000` 1075 1076Limits maximum response headers count. If set to 0, no limit will be applied. 1077 1078### `request.path` 1079 1080<!-- YAML 1081added: v0.4.0 1082--> 1083 1084* {string} The request path. 1085 1086### `request.method` 1087 1088<!-- YAML 1089added: v0.1.97 1090--> 1091 1092* {string} The request method. 1093 1094### `request.host` 1095 1096<!-- YAML 1097added: 1098 - v14.5.0 1099 - v12.19.0 1100--> 1101 1102* {string} The request host. 1103 1104### `request.protocol` 1105 1106<!-- YAML 1107added: 1108 - v14.5.0 1109 - v12.19.0 1110--> 1111 1112* {string} The request protocol. 1113 1114### `request.removeHeader(name)` 1115 1116<!-- YAML 1117added: v1.6.0 1118--> 1119 1120* `name` {string} 1121 1122Removes a header that's already defined into headers object. 1123 1124```js 1125request.removeHeader('Content-Type'); 1126``` 1127 1128### `request.reusedSocket` 1129 1130<!-- YAML 1131added: 1132 - v13.0.0 1133 - v12.16.0 1134--> 1135 1136* {boolean} Whether the request is send through a reused socket. 1137 1138When sending request through a keep-alive enabled agent, the underlying socket 1139might be reused. But if server closes connection at unfortunate time, client 1140may run into a 'ECONNRESET' error. 1141 1142```mjs 1143import http from 'node:http'; 1144 1145// Server has a 5 seconds keep-alive timeout by default 1146http 1147 .createServer((req, res) => { 1148 res.write('hello\n'); 1149 res.end(); 1150 }) 1151 .listen(3000); 1152 1153setInterval(() => { 1154 // Adapting a keep-alive agent 1155 http.get('http://localhost:3000', { agent }, (res) => { 1156 res.on('data', (data) => { 1157 // Do nothing 1158 }); 1159 }); 1160}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout 1161``` 1162 1163```cjs 1164const http = require('node:http'); 1165 1166// Server has a 5 seconds keep-alive timeout by default 1167http 1168 .createServer((req, res) => { 1169 res.write('hello\n'); 1170 res.end(); 1171 }) 1172 .listen(3000); 1173 1174setInterval(() => { 1175 // Adapting a keep-alive agent 1176 http.get('http://localhost:3000', { agent }, (res) => { 1177 res.on('data', (data) => { 1178 // Do nothing 1179 }); 1180 }); 1181}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout 1182``` 1183 1184By marking a request whether it reused socket or not, we can do 1185automatic error retry base on it. 1186 1187```mjs 1188import http from 'node:http'; 1189const agent = new http.Agent({ keepAlive: true }); 1190 1191function retriableRequest() { 1192 const req = http 1193 .get('http://localhost:3000', { agent }, (res) => { 1194 // ... 1195 }) 1196 .on('error', (err) => { 1197 // Check if retry is needed 1198 if (req.reusedSocket && err.code === 'ECONNRESET') { 1199 retriableRequest(); 1200 } 1201 }); 1202} 1203 1204retriableRequest(); 1205``` 1206 1207```cjs 1208const http = require('node:http'); 1209const agent = new http.Agent({ keepAlive: true }); 1210 1211function retriableRequest() { 1212 const req = http 1213 .get('http://localhost:3000', { agent }, (res) => { 1214 // ... 1215 }) 1216 .on('error', (err) => { 1217 // Check if retry is needed 1218 if (req.reusedSocket && err.code === 'ECONNRESET') { 1219 retriableRequest(); 1220 } 1221 }); 1222} 1223 1224retriableRequest(); 1225``` 1226 1227### `request.setHeader(name, value)` 1228 1229<!-- YAML 1230added: v1.6.0 1231--> 1232 1233* `name` {string} 1234* `value` {any} 1235 1236Sets a single header value for headers object. If this header already exists in 1237the to-be-sent headers, its value will be replaced. Use an array of strings 1238here to send multiple headers with the same name. Non-string values will be 1239stored without modification. Therefore, [`request.getHeader()`][] may return 1240non-string values. However, the non-string values will be converted to strings 1241for network transmission. 1242 1243```js 1244request.setHeader('Content-Type', 'application/json'); 1245``` 1246 1247or 1248 1249```js 1250request.setHeader('Cookie', ['type=ninja', 'language=javascript']); 1251``` 1252 1253When the value is a string an exception will be thrown if it contains 1254characters outside the `latin1` encoding. 1255 1256If you need to pass UTF-8 characters in the value please encode the value 1257using the [RFC 8187][] standard. 1258 1259```js 1260const filename = 'Rock .txt'; 1261request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`); 1262``` 1263 1264### `request.setNoDelay([noDelay])` 1265 1266<!-- YAML 1267added: v0.5.9 1268--> 1269 1270* `noDelay` {boolean} 1271 1272Once a socket is assigned to this request and is connected 1273[`socket.setNoDelay()`][] will be called. 1274 1275### `request.setSocketKeepAlive([enable][, initialDelay])` 1276 1277<!-- YAML 1278added: v0.5.9 1279--> 1280 1281* `enable` {boolean} 1282* `initialDelay` {number} 1283 1284Once a socket is assigned to this request and is connected 1285[`socket.setKeepAlive()`][] will be called. 1286 1287### `request.setTimeout(timeout[, callback])` 1288 1289<!-- YAML 1290added: v0.5.9 1291changes: 1292 - version: v9.0.0 1293 pr-url: https://github.com/nodejs/node/pull/8895 1294 description: Consistently set socket timeout only when the socket connects. 1295--> 1296 1297* `timeout` {number} Milliseconds before a request times out. 1298* `callback` {Function} Optional function to be called when a timeout occurs. 1299 Same as binding to the `'timeout'` event. 1300* Returns: {http.ClientRequest} 1301 1302Once a socket is assigned to this request and is connected 1303[`socket.setTimeout()`][] will be called. 1304 1305### `request.socket` 1306 1307<!-- YAML 1308added: v0.3.0 1309--> 1310 1311* {stream.Duplex} 1312 1313Reference to the underlying socket. Usually users will not want to access 1314this property. In particular, the socket will not emit `'readable'` events 1315because of how the protocol parser attaches to the socket. 1316 1317```mjs 1318import http from 'node:http'; 1319const options = { 1320 host: 'www.google.com', 1321}; 1322const req = http.get(options); 1323req.end(); 1324req.once('response', (res) => { 1325 const ip = req.socket.localAddress; 1326 const port = req.socket.localPort; 1327 console.log(`Your IP address is ${ip} and your source port is ${port}.`); 1328 // Consume response object 1329}); 1330``` 1331 1332```cjs 1333const http = require('node:http'); 1334const options = { 1335 host: 'www.google.com', 1336}; 1337const req = http.get(options); 1338req.end(); 1339req.once('response', (res) => { 1340 const ip = req.socket.localAddress; 1341 const port = req.socket.localPort; 1342 console.log(`Your IP address is ${ip} and your source port is ${port}.`); 1343 // Consume response object 1344}); 1345``` 1346 1347This property is guaranteed to be an instance of the {net.Socket} class, 1348a subclass of {stream.Duplex}, unless the user specified a socket 1349type other than {net.Socket}. 1350 1351### `request.uncork()` 1352 1353<!-- YAML 1354added: 1355 - v13.2.0 1356 - v12.16.0 1357--> 1358 1359See [`writable.uncork()`][]. 1360 1361### `request.writableEnded` 1362 1363<!-- YAML 1364added: v12.9.0 1365--> 1366 1367* {boolean} 1368 1369Is `true` after [`request.end()`][] has been called. This property 1370does not indicate whether the data has been flushed, for this use 1371[`request.writableFinished`][] instead. 1372 1373### `request.writableFinished` 1374 1375<!-- YAML 1376added: v12.7.0 1377--> 1378 1379* {boolean} 1380 1381Is `true` if all data has been flushed to the underlying system, immediately 1382before the [`'finish'`][] event is emitted. 1383 1384### `request.write(chunk[, encoding][, callback])` 1385 1386<!-- YAML 1387added: v0.1.29 1388changes: 1389 - version: v15.0.0 1390 pr-url: https://github.com/nodejs/node/pull/33155 1391 description: The `chunk` parameter can now be a `Uint8Array`. 1392--> 1393 1394* `chunk` {string|Buffer|Uint8Array} 1395* `encoding` {string} 1396* `callback` {Function} 1397* Returns: {boolean} 1398 1399Sends a chunk of the body. This method can be called multiple times. If no 1400`Content-Length` is set, data will automatically be encoded in HTTP Chunked 1401transfer encoding, so that server knows when the data ends. The 1402`Transfer-Encoding: chunked` header is added. Calling [`request.end()`][] 1403is necessary to finish sending the request. 1404 1405The `encoding` argument is optional and only applies when `chunk` is a string. 1406Defaults to `'utf8'`. 1407 1408The `callback` argument is optional and will be called when this chunk of data 1409is flushed, but only if the chunk is non-empty. 1410 1411Returns `true` if the entire data was flushed successfully to the kernel 1412buffer. Returns `false` if all or part of the data was queued in user memory. 1413`'drain'` will be emitted when the buffer is free again. 1414 1415When `write` function is called with empty string or buffer, it does 1416nothing and waits for more input. 1417 1418## Class: `http.Server` 1419 1420<!-- YAML 1421added: v0.1.17 1422--> 1423 1424* Extends: {net.Server} 1425 1426### Event: `'checkContinue'` 1427 1428<!-- YAML 1429added: v0.3.0 1430--> 1431 1432* `request` {http.IncomingMessage} 1433* `response` {http.ServerResponse} 1434 1435Emitted each time a request with an HTTP `Expect: 100-continue` is received. 1436If this event is not listened for, the server will automatically respond 1437with a `100 Continue` as appropriate. 1438 1439Handling this event involves calling [`response.writeContinue()`][] if the 1440client should continue to send the request body, or generating an appropriate 1441HTTP response (e.g. 400 Bad Request) if the client should not continue to send 1442the request body. 1443 1444When this event is emitted and handled, the [`'request'`][] event will 1445not be emitted. 1446 1447### Event: `'checkExpectation'` 1448 1449<!-- YAML 1450added: v5.5.0 1451--> 1452 1453* `request` {http.IncomingMessage} 1454* `response` {http.ServerResponse} 1455 1456Emitted each time a request with an HTTP `Expect` header is received, where the 1457value is not `100-continue`. If this event is not listened for, the server will 1458automatically respond with a `417 Expectation Failed` as appropriate. 1459 1460When this event is emitted and handled, the [`'request'`][] event will 1461not be emitted. 1462 1463### Event: `'clientError'` 1464 1465<!-- YAML 1466added: v0.1.94 1467changes: 1468 - version: v12.0.0 1469 pr-url: https://github.com/nodejs/node/pull/25605 1470 description: The default behavior will return a 431 Request Header 1471 Fields Too Large if a HPE_HEADER_OVERFLOW error occurs. 1472 - version: v9.4.0 1473 pr-url: https://github.com/nodejs/node/pull/17672 1474 description: The `rawPacket` is the current buffer that just parsed. Adding 1475 this buffer to the error object of `'clientError'` event is to 1476 make it possible that developers can log the broken packet. 1477 - version: v6.0.0 1478 pr-url: https://github.com/nodejs/node/pull/4557 1479 description: The default action of calling `.destroy()` on the `socket` 1480 will no longer take place if there are listeners attached 1481 for `'clientError'`. 1482--> 1483 1484* `exception` {Error} 1485* `socket` {stream.Duplex} 1486 1487If a client connection emits an `'error'` event, it will be forwarded here. 1488Listener of this event is responsible for closing/destroying the underlying 1489socket. For example, one may wish to more gracefully close the socket with a 1490custom HTTP response instead of abruptly severing the connection. The socket 1491**must be closed or destroyed** before the listener ends. 1492 1493This event is guaranteed to be passed an instance of the {net.Socket} class, 1494a subclass of {stream.Duplex}, unless the user specifies a socket 1495type other than {net.Socket}. 1496 1497Default behavior is to try close the socket with a HTTP '400 Bad Request', 1498or a HTTP '431 Request Header Fields Too Large' in the case of a 1499[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable or headers 1500of the current attached [`http.ServerResponse`][] has been sent, it is 1501immediately destroyed. 1502 1503`socket` is the [`net.Socket`][] object that the error originated from. 1504 1505```mjs 1506import http from 'node:http'; 1507 1508const server = http.createServer((req, res) => { 1509 res.end(); 1510}); 1511server.on('clientError', (err, socket) => { 1512 socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); 1513}); 1514server.listen(8000); 1515``` 1516 1517```cjs 1518const http = require('node:http'); 1519 1520const server = http.createServer((req, res) => { 1521 res.end(); 1522}); 1523server.on('clientError', (err, socket) => { 1524 socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); 1525}); 1526server.listen(8000); 1527``` 1528 1529When the `'clientError'` event occurs, there is no `request` or `response` 1530object, so any HTTP response sent, including response headers and payload, 1531_must_ be written directly to the `socket` object. Care must be taken to 1532ensure the response is a properly formatted HTTP response message. 1533 1534`err` is an instance of `Error` with two extra columns: 1535 1536* `bytesParsed`: the bytes count of request packet that Node.js may have parsed 1537 correctly; 1538* `rawPacket`: the raw packet of current request. 1539 1540In some cases, the client has already received the response and/or the socket 1541has already been destroyed, like in case of `ECONNRESET` errors. Before 1542trying to send data to the socket, it is better to check that it is still 1543writable. 1544 1545```js 1546server.on('clientError', (err, socket) => { 1547 if (err.code === 'ECONNRESET' || !socket.writable) { 1548 return; 1549 } 1550 1551 socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); 1552}); 1553``` 1554 1555### Event: `'close'` 1556 1557<!-- YAML 1558added: v0.1.4 1559--> 1560 1561Emitted when the server closes. 1562 1563### Event: `'connect'` 1564 1565<!-- YAML 1566added: v0.7.0 1567--> 1568 1569* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in 1570 the [`'request'`][] event 1571* `socket` {stream.Duplex} Network socket between the server and client 1572* `head` {Buffer} The first packet of the tunneling stream (may be empty) 1573 1574Emitted each time a client requests an HTTP `CONNECT` method. If this event is 1575not listened for, then clients requesting a `CONNECT` method will have their 1576connections closed. 1577 1578This event is guaranteed to be passed an instance of the {net.Socket} class, 1579a subclass of {stream.Duplex}, unless the user specifies a socket 1580type other than {net.Socket}. 1581 1582After this event is emitted, the request's socket will not have a `'data'` 1583event listener, meaning it will need to be bound in order to handle data 1584sent to the server on that socket. 1585 1586### Event: `'connection'` 1587 1588<!-- YAML 1589added: v0.1.0 1590--> 1591 1592* `socket` {stream.Duplex} 1593 1594This event is emitted when a new TCP stream is established. `socket` is 1595typically an object of type [`net.Socket`][]. Usually users will not want to 1596access this event. In particular, the socket will not emit `'readable'` events 1597because of how the protocol parser attaches to the socket. The `socket` can 1598also be accessed at `request.socket`. 1599 1600This event can also be explicitly emitted by users to inject connections 1601into the HTTP server. In that case, any [`Duplex`][] stream can be passed. 1602 1603If `socket.setTimeout()` is called here, the timeout will be replaced with 1604`server.keepAliveTimeout` when the socket has served a request (if 1605`server.keepAliveTimeout` is non-zero). 1606 1607This event is guaranteed to be passed an instance of the {net.Socket} class, 1608a subclass of {stream.Duplex}, unless the user specifies a socket 1609type other than {net.Socket}. 1610 1611### Event: `'dropRequest'` 1612 1613<!-- YAML 1614added: v18.7.0 1615--> 1616 1617* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in 1618 the [`'request'`][] event 1619* `socket` {stream.Duplex} Network socket between the server and client 1620 1621When the number of requests on a socket reaches the threshold of 1622`server.maxRequestsPerSocket`, the server will drop new requests 1623and emit `'dropRequest'` event instead, then send `503` to client. 1624 1625### Event: `'request'` 1626 1627<!-- YAML 1628added: v0.1.0 1629--> 1630 1631* `request` {http.IncomingMessage} 1632* `response` {http.ServerResponse} 1633 1634Emitted each time there is a request. There may be multiple requests 1635per connection (in the case of HTTP Keep-Alive connections). 1636 1637### Event: `'upgrade'` 1638 1639<!-- YAML 1640added: v0.1.94 1641changes: 1642 - version: v10.0.0 1643 pr-url: https://github.com/nodejs/node/pull/19981 1644 description: Not listening to this event no longer causes the socket 1645 to be destroyed if a client sends an Upgrade header. 1646--> 1647 1648* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in 1649 the [`'request'`][] event 1650* `socket` {stream.Duplex} Network socket between the server and client 1651* `head` {Buffer} The first packet of the upgraded stream (may be empty) 1652 1653Emitted each time a client requests an HTTP upgrade. Listening to this event 1654is optional and clients cannot insist on a protocol change. 1655 1656After this event is emitted, the request's socket will not have a `'data'` 1657event listener, meaning it will need to be bound in order to handle data 1658sent to the server on that socket. 1659 1660This event is guaranteed to be passed an instance of the {net.Socket} class, 1661a subclass of {stream.Duplex}, unless the user specifies a socket 1662type other than {net.Socket}. 1663 1664### `server.close([callback])` 1665 1666<!-- YAML 1667added: v0.1.90 1668--> 1669 1670* `callback` {Function} 1671 1672Stops the server from accepting new connections. See [`net.Server.close()`][]. 1673 1674### `server.closeAllConnections()` 1675 1676<!-- YAML 1677added: v18.2.0 1678--> 1679 1680Closes all connections connected to this server. 1681 1682### `server.closeIdleConnections()` 1683 1684<!-- YAML 1685added: v18.2.0 1686--> 1687 1688Closes all connections connected to this server which are not sending a request 1689or waiting for a response. 1690 1691### `server.headersTimeout` 1692 1693<!-- YAML 1694added: 1695 - v11.3.0 1696 - v10.14.0 1697changes: 1698 - version: v18.14.0 1699 pr-url: https://github.com/nodejs/node/pull/45778 1700 description: The default is now set to the minimum between 60000 (60 seconds) or `requestTimeout`. 1701--> 1702 1703* {number} **Default:** The minimum between [`server.requestTimeout`][] or `60000`. 1704 1705Limit the amount of time the parser will wait to receive the complete HTTP 1706headers. 1707 1708If the timeout expires, the server responds with status 408 without 1709forwarding the request to the request listener and then closes the connection. 1710 1711It must be set to a non-zero value (e.g. 120 seconds) to protect against 1712potential Denial-of-Service attacks in case the server is deployed without a 1713reverse proxy in front. 1714 1715### `server.listen()` 1716 1717Starts the HTTP server listening for connections. 1718This method is identical to [`server.listen()`][] from [`net.Server`][]. 1719 1720### `server.listening` 1721 1722<!-- YAML 1723added: v5.7.0 1724--> 1725 1726* {boolean} Indicates whether or not the server is listening for connections. 1727 1728### `server.maxHeadersCount` 1729 1730<!-- YAML 1731added: v0.7.0 1732--> 1733 1734* {number} **Default:** `2000` 1735 1736Limits maximum incoming headers count. If set to 0, no limit will be applied. 1737 1738### `server.requestTimeout` 1739 1740<!-- YAML 1741added: v14.11.0 1742changes: 1743 - version: v18.0.0 1744 pr-url: https://github.com/nodejs/node/pull/41263 1745 description: The default request timeout changed 1746 from no timeout to 300s (5 minutes). 1747--> 1748 1749* {number} **Default:** `300000` 1750 1751Sets the timeout value in milliseconds for receiving the entire request from 1752the client. 1753 1754If the timeout expires, the server responds with status 408 without 1755forwarding the request to the request listener and then closes the connection. 1756 1757It must be set to a non-zero value (e.g. 120 seconds) to protect against 1758potential Denial-of-Service attacks in case the server is deployed without a 1759reverse proxy in front. 1760 1761### `server.setTimeout([msecs][, callback])` 1762 1763<!-- YAML 1764added: v0.9.12 1765changes: 1766 - version: v13.0.0 1767 pr-url: https://github.com/nodejs/node/pull/27558 1768 description: The default timeout changed from 120s to 0 (no timeout). 1769--> 1770 1771* `msecs` {number} **Default:** 0 (no timeout) 1772* `callback` {Function} 1773* Returns: {http.Server} 1774 1775Sets the timeout value for sockets, and emits a `'timeout'` event on 1776the Server object, passing the socket as an argument, if a timeout 1777occurs. 1778 1779If there is a `'timeout'` event listener on the Server object, then it 1780will be called with the timed-out socket as an argument. 1781 1782By default, the Server does not timeout sockets. However, if a callback 1783is assigned to the Server's `'timeout'` event, timeouts must be handled 1784explicitly. 1785 1786### `server.maxRequestsPerSocket` 1787 1788<!-- YAML 1789added: v16.10.0 1790--> 1791 1792* {number} Requests per socket. **Default:** 0 (no limit) 1793 1794The maximum number of requests socket can handle 1795before closing keep alive connection. 1796 1797A value of `0` will disable the limit. 1798 1799When the limit is reached it will set the `Connection` header value to `close`, 1800but will not actually close the connection, subsequent requests sent 1801after the limit is reached will get `503 Service Unavailable` as a response. 1802 1803### `server.timeout` 1804 1805<!-- YAML 1806added: v0.9.12 1807changes: 1808 - version: v13.0.0 1809 pr-url: https://github.com/nodejs/node/pull/27558 1810 description: The default timeout changed from 120s to 0 (no timeout). 1811--> 1812 1813* {number} Timeout in milliseconds. **Default:** 0 (no timeout) 1814 1815The number of milliseconds of inactivity before a socket is presumed 1816to have timed out. 1817 1818A value of `0` will disable the timeout behavior on incoming connections. 1819 1820The socket timeout logic is set up on connection, so changing this 1821value only affects new connections to the server, not any existing connections. 1822 1823### `server.keepAliveTimeout` 1824 1825<!-- YAML 1826added: v8.0.0 1827--> 1828 1829* {number} Timeout in milliseconds. **Default:** `5000` (5 seconds). 1830 1831The number of milliseconds of inactivity a server needs to wait for additional 1832incoming data, after it has finished writing the last response, before a socket 1833will be destroyed. If the server receives new data before the keep-alive 1834timeout has fired, it will reset the regular inactivity timeout, i.e., 1835[`server.timeout`][]. 1836 1837A value of `0` will disable the keep-alive timeout behavior on incoming 1838connections. 1839A value of `0` makes the http server behave similarly to Node.js versions prior 1840to 8.0.0, which did not have a keep-alive timeout. 1841 1842The socket timeout logic is set up on connection, so changing this value only 1843affects new connections to the server, not any existing connections. 1844 1845## Class: `http.ServerResponse` 1846 1847<!-- YAML 1848added: v0.1.17 1849--> 1850 1851* Extends: {http.OutgoingMessage} 1852 1853This object is created internally by an HTTP server, not by the user. It is 1854passed as the second parameter to the [`'request'`][] event. 1855 1856### Event: `'close'` 1857 1858<!-- YAML 1859added: v0.6.7 1860--> 1861 1862Indicates that the response is completed, or its underlying connection was 1863terminated prematurely (before the response completion). 1864 1865### Event: `'finish'` 1866 1867<!-- YAML 1868added: v0.3.6 1869--> 1870 1871Emitted when the response has been sent. More specifically, this event is 1872emitted when the last segment of the response headers and body have been 1873handed off to the operating system for transmission over the network. It 1874does not imply that the client has received anything yet. 1875 1876### `response.addTrailers(headers)` 1877 1878<!-- YAML 1879added: v0.3.0 1880--> 1881 1882* `headers` {Object} 1883 1884This method adds HTTP trailing headers (a header but at the end of the 1885message) to the response. 1886 1887Trailers will **only** be emitted if chunked encoding is used for the 1888response; if it is not (e.g. if the request was HTTP/1.0), they will 1889be silently discarded. 1890 1891HTTP requires the `Trailer` header to be sent in order to 1892emit trailers, with a list of the header fields in its value. E.g., 1893 1894```js 1895response.writeHead(200, { 'Content-Type': 'text/plain', 1896 'Trailer': 'Content-MD5' }); 1897response.write(fileData); 1898response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); 1899response.end(); 1900``` 1901 1902Attempting to set a header field name or value that contains invalid characters 1903will result in a [`TypeError`][] being thrown. 1904 1905### `response.connection` 1906 1907<!-- YAML 1908added: v0.3.0 1909deprecated: v13.0.0 1910--> 1911 1912> Stability: 0 - Deprecated. Use [`response.socket`][]. 1913 1914* {stream.Duplex} 1915 1916See [`response.socket`][]. 1917 1918### `response.cork()` 1919 1920<!-- YAML 1921added: 1922 - v13.2.0 1923 - v12.16.0 1924--> 1925 1926See [`writable.cork()`][]. 1927 1928### `response.end([data[, encoding]][, callback])` 1929 1930<!-- YAML 1931added: v0.1.90 1932changes: 1933 - version: v15.0.0 1934 pr-url: https://github.com/nodejs/node/pull/33155 1935 description: The `data` parameter can now be a `Uint8Array`. 1936 - version: v10.0.0 1937 pr-url: https://github.com/nodejs/node/pull/18780 1938 description: This method now returns a reference to `ServerResponse`. 1939--> 1940 1941* `data` {string|Buffer|Uint8Array} 1942* `encoding` {string} 1943* `callback` {Function} 1944* Returns: {this} 1945 1946This method signals to the server that all of the response headers and body 1947have been sent; that server should consider this message complete. 1948The method, `response.end()`, MUST be called on each response. 1949 1950If `data` is specified, it is similar in effect to calling 1951[`response.write(data, encoding)`][] followed by `response.end(callback)`. 1952 1953If `callback` is specified, it will be called when the response stream 1954is finished. 1955 1956### `response.finished` 1957 1958<!-- YAML 1959added: v0.0.2 1960deprecated: 1961 - v13.4.0 1962 - v12.16.0 1963--> 1964 1965> Stability: 0 - Deprecated. Use [`response.writableEnded`][]. 1966 1967* {boolean} 1968 1969The `response.finished` property will be `true` if [`response.end()`][] 1970has been called. 1971 1972### `response.flushHeaders()` 1973 1974<!-- YAML 1975added: v1.6.0 1976--> 1977 1978Flushes the response headers. See also: [`request.flushHeaders()`][]. 1979 1980### `response.getHeader(name)` 1981 1982<!-- YAML 1983added: v0.4.0 1984--> 1985 1986* `name` {string} 1987* Returns: {any} 1988 1989Reads out a header that's already been queued but not sent to the client. 1990The name is case-insensitive. The type of the return value depends 1991on the arguments provided to [`response.setHeader()`][]. 1992 1993```js 1994response.setHeader('Content-Type', 'text/html'); 1995response.setHeader('Content-Length', Buffer.byteLength(body)); 1996response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 1997const contentType = response.getHeader('content-type'); 1998// contentType is 'text/html' 1999const contentLength = response.getHeader('Content-Length'); 2000// contentLength is of type number 2001const setCookie = response.getHeader('set-cookie'); 2002// setCookie is of type string[] 2003``` 2004 2005### `response.getHeaderNames()` 2006 2007<!-- YAML 2008added: v7.7.0 2009--> 2010 2011* Returns: {string\[]} 2012 2013Returns an array containing the unique names of the current outgoing headers. 2014All header names are lowercase. 2015 2016```js 2017response.setHeader('Foo', 'bar'); 2018response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 2019 2020const headerNames = response.getHeaderNames(); 2021// headerNames === ['foo', 'set-cookie'] 2022``` 2023 2024### `response.getHeaders()` 2025 2026<!-- YAML 2027added: v7.7.0 2028--> 2029 2030* Returns: {Object} 2031 2032Returns a shallow copy of the current outgoing headers. Since a shallow copy 2033is used, array values may be mutated without additional calls to various 2034header-related http module methods. The keys of the returned object are the 2035header names and the values are the respective header values. All header names 2036are lowercase. 2037 2038The object returned by the `response.getHeaders()` method _does not_ 2039prototypically inherit from the JavaScript `Object`. This means that typical 2040`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others 2041are not defined and _will not work_. 2042 2043```js 2044response.setHeader('Foo', 'bar'); 2045response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 2046 2047const headers = response.getHeaders(); 2048// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 2049``` 2050 2051### `response.hasHeader(name)` 2052 2053<!-- YAML 2054added: v7.7.0 2055--> 2056 2057* `name` {string} 2058* Returns: {boolean} 2059 2060Returns `true` if the header identified by `name` is currently set in the 2061outgoing headers. The header name matching is case-insensitive. 2062 2063```js 2064const hasContentType = response.hasHeader('content-type'); 2065``` 2066 2067### `response.headersSent` 2068 2069<!-- YAML 2070added: v0.9.3 2071--> 2072 2073* {boolean} 2074 2075Boolean (read-only). True if headers were sent, false otherwise. 2076 2077### `response.removeHeader(name)` 2078 2079<!-- YAML 2080added: v0.4.0 2081--> 2082 2083* `name` {string} 2084 2085Removes a header that's queued for implicit sending. 2086 2087```js 2088response.removeHeader('Content-Encoding'); 2089``` 2090 2091### `response.req` 2092 2093<!-- YAML 2094added: v15.7.0 2095--> 2096 2097* {http.IncomingMessage} 2098 2099A reference to the original HTTP `request` object. 2100 2101### `response.sendDate` 2102 2103<!-- YAML 2104added: v0.7.5 2105--> 2106 2107* {boolean} 2108 2109When true, the Date header will be automatically generated and sent in 2110the response if it is not already present in the headers. Defaults to true. 2111 2112This should only be disabled for testing; HTTP requires the Date header 2113in responses. 2114 2115### `response.setHeader(name, value)` 2116 2117<!-- YAML 2118added: v0.4.0 2119--> 2120 2121* `name` {string} 2122* `value` {any} 2123* Returns: {http.ServerResponse} 2124 2125Returns the response object. 2126 2127Sets a single header value for implicit headers. If this header already exists 2128in the to-be-sent headers, its value will be replaced. Use an array of strings 2129here to send multiple headers with the same name. Non-string values will be 2130stored without modification. Therefore, [`response.getHeader()`][] may return 2131non-string values. However, the non-string values will be converted to strings 2132for network transmission. The same response object is returned to the caller, 2133to enable call chaining. 2134 2135```js 2136response.setHeader('Content-Type', 'text/html'); 2137``` 2138 2139or 2140 2141```js 2142response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 2143``` 2144 2145Attempting to set a header field name or value that contains invalid characters 2146will result in a [`TypeError`][] being thrown. 2147 2148When headers have been set with [`response.setHeader()`][], they will be merged 2149with any headers passed to [`response.writeHead()`][], with the headers passed 2150to [`response.writeHead()`][] given precedence. 2151 2152```js 2153// Returns content-type = text/plain 2154const server = http.createServer((req, res) => { 2155 res.setHeader('Content-Type', 'text/html'); 2156 res.setHeader('X-Foo', 'bar'); 2157 res.writeHead(200, { 'Content-Type': 'text/plain' }); 2158 res.end('ok'); 2159}); 2160``` 2161 2162If [`response.writeHead()`][] method is called and this method has not been 2163called, it will directly write the supplied header values onto the network 2164channel without caching internally, and the [`response.getHeader()`][] on the 2165header will not yield the expected result. If progressive population of headers 2166is desired with potential future retrieval and modification, use 2167[`response.setHeader()`][] instead of [`response.writeHead()`][]. 2168 2169### `response.setTimeout(msecs[, callback])` 2170 2171<!-- YAML 2172added: v0.9.12 2173--> 2174 2175* `msecs` {number} 2176* `callback` {Function} 2177* Returns: {http.ServerResponse} 2178 2179Sets the Socket's timeout value to `msecs`. If a callback is 2180provided, then it is added as a listener on the `'timeout'` event on 2181the response object. 2182 2183If no `'timeout'` listener is added to the request, the response, or 2184the server, then sockets are destroyed when they time out. If a handler is 2185assigned to the request, the response, or the server's `'timeout'` events, 2186timed out sockets must be handled explicitly. 2187 2188### `response.socket` 2189 2190<!-- YAML 2191added: v0.3.0 2192--> 2193 2194* {stream.Duplex} 2195 2196Reference to the underlying socket. Usually users will not want to access 2197this property. In particular, the socket will not emit `'readable'` events 2198because of how the protocol parser attaches to the socket. After 2199`response.end()`, the property is nulled. 2200 2201```mjs 2202import http from 'node:http'; 2203const server = http.createServer((req, res) => { 2204 const ip = res.socket.remoteAddress; 2205 const port = res.socket.remotePort; 2206 res.end(`Your IP address is ${ip} and your source port is ${port}.`); 2207}).listen(3000); 2208``` 2209 2210```cjs 2211const http = require('node:http'); 2212const server = http.createServer((req, res) => { 2213 const ip = res.socket.remoteAddress; 2214 const port = res.socket.remotePort; 2215 res.end(`Your IP address is ${ip} and your source port is ${port}.`); 2216}).listen(3000); 2217``` 2218 2219This property is guaranteed to be an instance of the {net.Socket} class, 2220a subclass of {stream.Duplex}, unless the user specified a socket 2221type other than {net.Socket}. 2222 2223### `response.statusCode` 2224 2225<!-- YAML 2226added: v0.4.0 2227--> 2228 2229* {number} **Default:** `200` 2230 2231When using implicit headers (not calling [`response.writeHead()`][] explicitly), 2232this property controls the status code that will be sent to the client when 2233the headers get flushed. 2234 2235```js 2236response.statusCode = 404; 2237``` 2238 2239After response header was sent to the client, this property indicates the 2240status code which was sent out. 2241 2242### `response.statusMessage` 2243 2244<!-- YAML 2245added: v0.11.8 2246--> 2247 2248* {string} 2249 2250When using implicit headers (not calling [`response.writeHead()`][] explicitly), 2251this property controls the status message that will be sent to the client when 2252the headers get flushed. If this is left as `undefined` then the standard 2253message for the status code will be used. 2254 2255```js 2256response.statusMessage = 'Not found'; 2257``` 2258 2259After response header was sent to the client, this property indicates the 2260status message which was sent out. 2261 2262### `response.strictContentLength` 2263 2264<!-- YAML 2265added: 2266 - v18.10.0 2267 - v16.18.0 2268--> 2269 2270* {boolean} **Default:** `false` 2271 2272If set to `true`, Node.js will check whether the `Content-Length` 2273header value and the size of the body, in bytes, are equal. 2274Mismatching the `Content-Length` header value will result 2275in an `Error` being thrown, identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][]. 2276 2277### `response.uncork()` 2278 2279<!-- YAML 2280added: 2281 - v13.2.0 2282 - v12.16.0 2283--> 2284 2285See [`writable.uncork()`][]. 2286 2287### `response.writableEnded` 2288 2289<!-- YAML 2290added: v12.9.0 2291--> 2292 2293* {boolean} 2294 2295Is `true` after [`response.end()`][] has been called. This property 2296does not indicate whether the data has been flushed, for this use 2297[`response.writableFinished`][] instead. 2298 2299### `response.writableFinished` 2300 2301<!-- YAML 2302added: v12.7.0 2303--> 2304 2305* {boolean} 2306 2307Is `true` if all data has been flushed to the underlying system, immediately 2308before the [`'finish'`][] event is emitted. 2309 2310### `response.write(chunk[, encoding][, callback])` 2311 2312<!-- YAML 2313added: v0.1.29 2314changes: 2315 - version: v15.0.0 2316 pr-url: https://github.com/nodejs/node/pull/33155 2317 description: The `chunk` parameter can now be a `Uint8Array`. 2318--> 2319 2320* `chunk` {string|Buffer|Uint8Array} 2321* `encoding` {string} **Default:** `'utf8'` 2322* `callback` {Function} 2323* Returns: {boolean} 2324 2325If this method is called and [`response.writeHead()`][] has not been called, 2326it will switch to implicit header mode and flush the implicit headers. 2327 2328This sends a chunk of the response body. This method may 2329be called multiple times to provide successive parts of the body. 2330 2331Writing to the body is not allowed when the request method or response status 2332do not support content. If an attempt is made to write to the body for a 2333HEAD request or as part of a `204` or `304`response, a synchronous `Error` 2334with the code `ERR_HTTP_BODY_NOT_ALLOWED` is thrown. 2335 2336`chunk` can be a string or a buffer. If `chunk` is a string, 2337the second parameter specifies how to encode it into a byte stream. 2338`callback` will be called when this chunk of data is flushed. 2339 2340This is the raw HTTP body and has nothing to do with higher-level multi-part 2341body encodings that may be used. 2342 2343The first time [`response.write()`][] is called, it will send the buffered 2344header information and the first chunk of the body to the client. The second 2345time [`response.write()`][] is called, Node.js assumes data will be streamed, 2346and sends the new data separately. That is, the response is buffered up to the 2347first chunk of the body. 2348 2349Returns `true` if the entire data was flushed successfully to the kernel 2350buffer. Returns `false` if all or part of the data was queued in user memory. 2351`'drain'` will be emitted when the buffer is free again. 2352 2353### `response.writeContinue()` 2354 2355<!-- YAML 2356added: v0.3.0 2357--> 2358 2359Sends an HTTP/1.1 100 Continue message to the client, indicating that 2360the request body should be sent. See the [`'checkContinue'`][] event on 2361`Server`. 2362 2363### `response.writeEarlyHints(hints[, callback])` 2364 2365<!-- YAML 2366added: v18.11.0 2367changes: 2368 - version: v18.11.0 2369 pr-url: https://github.com/nodejs/node/pull/44820 2370 description: Allow passing hints as an object. 2371--> 2372 2373* `hints` {Object} 2374* `callback` {Function} 2375 2376Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, 2377indicating that the user agent can preload/preconnect the linked resources. 2378The `hints` is an object containing the values of headers to be sent with 2379early hints message. The optional `callback` argument will be called when 2380the response message has been written. 2381 2382**Example** 2383 2384```js 2385const earlyHintsLink = '</styles.css>; rel=preload; as=style'; 2386response.writeEarlyHints({ 2387 'link': earlyHintsLink, 2388}); 2389 2390const earlyHintsLinks = [ 2391 '</styles.css>; rel=preload; as=style', 2392 '</scripts.js>; rel=preload; as=script', 2393]; 2394response.writeEarlyHints({ 2395 'link': earlyHintsLinks, 2396 'x-trace-id': 'id for diagnostics', 2397}); 2398 2399const earlyHintsCallback = () => console.log('early hints message sent'); 2400response.writeEarlyHints({ 2401 'link': earlyHintsLinks, 2402}, earlyHintsCallback); 2403``` 2404 2405### `response.writeHead(statusCode[, statusMessage][, headers])` 2406 2407<!-- YAML 2408added: v0.1.30 2409changes: 2410 - version: v14.14.0 2411 pr-url: https://github.com/nodejs/node/pull/35274 2412 description: Allow passing headers as an array. 2413 - version: 2414 - v11.10.0 2415 - v10.17.0 2416 pr-url: https://github.com/nodejs/node/pull/25974 2417 description: Return `this` from `writeHead()` to allow chaining with 2418 `end()`. 2419 - version: 2420 - v5.11.0 2421 - v4.4.5 2422 pr-url: https://github.com/nodejs/node/pull/6291 2423 description: A `RangeError` is thrown if `statusCode` is not a number in 2424 the range `[100, 999]`. 2425--> 2426 2427* `statusCode` {number} 2428* `statusMessage` {string} 2429* `headers` {Object|Array} 2430* Returns: {http.ServerResponse} 2431 2432Sends a response header to the request. The status code is a 3-digit HTTP 2433status code, like `404`. The last argument, `headers`, are the response headers. 2434Optionally one can give a human-readable `statusMessage` as the second 2435argument. 2436 2437`headers` may be an `Array` where the keys and values are in the same list. 2438It is _not_ a list of tuples. So, the even-numbered offsets are key values, 2439and the odd-numbered offsets are the associated values. The array is in the same 2440format as `request.rawHeaders`. 2441 2442Returns a reference to the `ServerResponse`, so that calls can be chained. 2443 2444```js 2445const body = 'hello world'; 2446response 2447 .writeHead(200, { 2448 'Content-Length': Buffer.byteLength(body), 2449 'Content-Type': 'text/plain', 2450 }) 2451 .end(body); 2452``` 2453 2454This method must only be called once on a message and it must 2455be called before [`response.end()`][] is called. 2456 2457If [`response.write()`][] or [`response.end()`][] are called before calling 2458this, the implicit/mutable headers will be calculated and call this function. 2459 2460When headers have been set with [`response.setHeader()`][], they will be merged 2461with any headers passed to [`response.writeHead()`][], with the headers passed 2462to [`response.writeHead()`][] given precedence. 2463 2464If this method is called and [`response.setHeader()`][] has not been called, 2465it will directly write the supplied header values onto the network channel 2466without caching internally, and the [`response.getHeader()`][] on the header 2467will not yield the expected result. If progressive population of headers is 2468desired with potential future retrieval and modification, use 2469[`response.setHeader()`][] instead. 2470 2471```js 2472// Returns content-type = text/plain 2473const server = http.createServer((req, res) => { 2474 res.setHeader('Content-Type', 'text/html'); 2475 res.setHeader('X-Foo', 'bar'); 2476 res.writeHead(200, { 'Content-Type': 'text/plain' }); 2477 res.end('ok'); 2478}); 2479``` 2480 2481`Content-Length` is read in bytes, not characters. Use 2482[`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js 2483will check whether `Content-Length` and the length of the body which has 2484been transmitted are equal or not. 2485 2486Attempting to set a header field name or value that contains invalid characters 2487will result in a \[`Error`]\[] being thrown. 2488 2489### `response.writeProcessing()` 2490 2491<!-- YAML 2492added: v10.0.0 2493--> 2494 2495Sends a HTTP/1.1 102 Processing message to the client, indicating that 2496the request body should be sent. 2497 2498## Class: `http.IncomingMessage` 2499 2500<!-- YAML 2501added: v0.1.17 2502changes: 2503 - version: v15.5.0 2504 pr-url: https://github.com/nodejs/node/pull/33035 2505 description: The `destroyed` value returns `true` after the incoming data 2506 is consumed. 2507 - version: 2508 - v13.1.0 2509 - v12.16.0 2510 pr-url: https://github.com/nodejs/node/pull/30135 2511 description: The `readableHighWaterMark` value mirrors that of the socket. 2512--> 2513 2514* Extends: {stream.Readable} 2515 2516An `IncomingMessage` object is created by [`http.Server`][] or 2517[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][] 2518and [`'response'`][] event respectively. It may be used to access response 2519status, headers, and data. 2520 2521Different from its `socket` value which is a subclass of {stream.Duplex}, the 2522`IncomingMessage` itself extends {stream.Readable} and is created separately to 2523parse and emit the incoming HTTP headers and payload, as the underlying socket 2524may be reused multiple times in case of keep-alive. 2525 2526### Event: `'aborted'` 2527 2528<!-- YAML 2529added: v0.3.8 2530deprecated: 2531 - v17.0.0 2532 - v16.12.0 2533--> 2534 2535> Stability: 0 - Deprecated. Listen for `'close'` event instead. 2536 2537Emitted when the request has been aborted. 2538 2539### Event: `'close'` 2540 2541<!-- YAML 2542added: v0.4.2 2543changes: 2544 - version: v16.0.0 2545 pr-url: https://github.com/nodejs/node/pull/33035 2546 description: The close event is now emitted when the request has been completed and not when the 2547 underlying socket is closed. 2548--> 2549 2550Emitted when the request has been completed. 2551 2552### `message.aborted` 2553 2554<!-- YAML 2555added: v10.1.0 2556deprecated: 2557 - v17.0.0 2558 - v16.12.0 2559--> 2560 2561> Stability: 0 - Deprecated. Check `message.destroyed` from {stream.Readable}. 2562 2563* {boolean} 2564 2565The `message.aborted` property will be `true` if the request has 2566been aborted. 2567 2568### `message.complete` 2569 2570<!-- YAML 2571added: v0.3.0 2572--> 2573 2574* {boolean} 2575 2576The `message.complete` property will be `true` if a complete HTTP message has 2577been received and successfully parsed. 2578 2579This property is particularly useful as a means of determining if a client or 2580server fully transmitted a message before a connection was terminated: 2581 2582```js 2583const req = http.request({ 2584 host: '127.0.0.1', 2585 port: 8080, 2586 method: 'POST', 2587}, (res) => { 2588 res.resume(); 2589 res.on('end', () => { 2590 if (!res.complete) 2591 console.error( 2592 'The connection was terminated while the message was still being sent'); 2593 }); 2594}); 2595``` 2596 2597### `message.connection` 2598 2599<!-- YAML 2600added: v0.1.90 2601deprecated: v16.0.0 2602 --> 2603 2604> Stability: 0 - Deprecated. Use [`message.socket`][]. 2605 2606Alias for [`message.socket`][]. 2607 2608### `message.destroy([error])` 2609 2610<!-- YAML 2611added: v0.3.0 2612changes: 2613 - version: 2614 - v14.5.0 2615 - v12.19.0 2616 pr-url: https://github.com/nodejs/node/pull/32789 2617 description: The function returns `this` for consistency with other Readable 2618 streams. 2619--> 2620 2621* `error` {Error} 2622* Returns: {this} 2623 2624Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` 2625is provided, an `'error'` event is emitted on the socket and `error` is passed 2626as an argument to any listeners on the event. 2627 2628### `message.headers` 2629 2630<!-- YAML 2631added: v0.1.5 2632changes: 2633 - version: v18.14.0 2634 pr-url: https://github.com/nodejs/node/pull/45982 2635 description: >- 2636 The `joinDuplicateHeaders` option in the `http.request()` 2637 and `http.createServer()` functions ensures that duplicate 2638 headers are not discarded, but rather combined using a 2639 comma separator, in accordance with RFC 9110 Section 5.3. 2640 - version: v15.1.0 2641 pr-url: https://github.com/nodejs/node/pull/35281 2642 description: >- 2643 `message.headers` is now lazily computed using an accessor property 2644 on the prototype and is no longer enumerable. 2645--> 2646 2647* {Object} 2648 2649The request/response headers object. 2650 2651Key-value pairs of header names and values. Header names are lower-cased. 2652 2653```js 2654// Prints something like: 2655// 2656// { 'user-agent': 'curl/7.22.0', 2657// host: '127.0.0.1:8000', 2658// accept: '*/*' } 2659console.log(request.headers); 2660``` 2661 2662Duplicates in raw headers are handled in the following ways, depending on the 2663header name: 2664 2665* Duplicates of `age`, `authorization`, `content-length`, `content-type`, 2666 `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, 2667 `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, 2668 `retry-after`, `server`, or `user-agent` are discarded. 2669 To allow duplicate values of the headers listed above to be joined, 2670 use the option `joinDuplicateHeaders` in [`http.request()`][] 2671 and [`http.createServer()`][]. See RFC 9110 Section 5.3 for more 2672 information. 2673* `set-cookie` is always an array. Duplicates are added to the array. 2674* For duplicate `cookie` headers, the values are joined together with `; `. 2675* For all other headers, the values are joined together with `, `. 2676 2677### `message.headersDistinct` 2678 2679<!-- YAML 2680added: v18.3.0 2681--> 2682 2683* {Object} 2684 2685Similar to [`message.headers`][], but there is no join logic and the values are 2686always arrays of strings, even for headers received just once. 2687 2688```js 2689// Prints something like: 2690// 2691// { 'user-agent': ['curl/7.22.0'], 2692// host: ['127.0.0.1:8000'], 2693// accept: ['*/*'] } 2694console.log(request.headersDistinct); 2695``` 2696 2697### `message.httpVersion` 2698 2699<!-- YAML 2700added: v0.1.1 2701--> 2702 2703* {string} 2704 2705In case of server request, the HTTP version sent by the client. In the case of 2706client response, the HTTP version of the connected-to server. 2707Probably either `'1.1'` or `'1.0'`. 2708 2709Also `message.httpVersionMajor` is the first integer and 2710`message.httpVersionMinor` is the second. 2711 2712### `message.method` 2713 2714<!-- YAML 2715added: v0.1.1 2716--> 2717 2718* {string} 2719 2720**Only valid for request obtained from [`http.Server`][].** 2721 2722The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. 2723 2724### `message.rawHeaders` 2725 2726<!-- YAML 2727added: v0.11.6 2728--> 2729 2730* {string\[]} 2731 2732The raw request/response headers list exactly as they were received. 2733 2734The keys and values are in the same list. It is _not_ a 2735list of tuples. So, the even-numbered offsets are key values, and the 2736odd-numbered offsets are the associated values. 2737 2738Header names are not lowercased, and duplicates are not merged. 2739 2740```js 2741// Prints something like: 2742// 2743// [ 'user-agent', 2744// 'this is invalid because there can be only one', 2745// 'User-Agent', 2746// 'curl/7.22.0', 2747// 'Host', 2748// '127.0.0.1:8000', 2749// 'ACCEPT', 2750// '*/*' ] 2751console.log(request.rawHeaders); 2752``` 2753 2754### `message.rawTrailers` 2755 2756<!-- YAML 2757added: v0.11.6 2758--> 2759 2760* {string\[]} 2761 2762The raw request/response trailer keys and values exactly as they were 2763received. Only populated at the `'end'` event. 2764 2765### `message.setTimeout(msecs[, callback])` 2766 2767<!-- YAML 2768added: v0.5.9 2769--> 2770 2771* `msecs` {number} 2772* `callback` {Function} 2773* Returns: {http.IncomingMessage} 2774 2775Calls `message.socket.setTimeout(msecs, callback)`. 2776 2777### `message.socket` 2778 2779<!-- YAML 2780added: v0.3.0 2781--> 2782 2783* {stream.Duplex} 2784 2785The [`net.Socket`][] object associated with the connection. 2786 2787With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the 2788client's authentication details. 2789 2790This property is guaranteed to be an instance of the {net.Socket} class, 2791a subclass of {stream.Duplex}, unless the user specified a socket 2792type other than {net.Socket} or internally nulled. 2793 2794### `message.statusCode` 2795 2796<!-- YAML 2797added: v0.1.1 2798--> 2799 2800* {number} 2801 2802**Only valid for response obtained from [`http.ClientRequest`][].** 2803 2804The 3-digit HTTP response status code. E.G. `404`. 2805 2806### `message.statusMessage` 2807 2808<!-- YAML 2809added: v0.11.10 2810--> 2811 2812* {string} 2813 2814**Only valid for response obtained from [`http.ClientRequest`][].** 2815 2816The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server 2817Error`. 2818 2819### `message.trailers` 2820 2821<!-- YAML 2822added: v0.3.0 2823--> 2824 2825* {Object} 2826 2827The request/response trailers object. Only populated at the `'end'` event. 2828 2829### `message.trailersDistinct` 2830 2831<!-- YAML 2832added: v18.3.0 2833--> 2834 2835* {Object} 2836 2837Similar to [`message.trailers`][], but there is no join logic and the values are 2838always arrays of strings, even for headers received just once. 2839Only populated at the `'end'` event. 2840 2841### `message.url` 2842 2843<!-- YAML 2844added: v0.1.90 2845--> 2846 2847* {string} 2848 2849**Only valid for request obtained from [`http.Server`][].** 2850 2851Request URL string. This contains only the URL that is present in the actual 2852HTTP request. Take the following request: 2853 2854```http 2855GET /status?name=ryan HTTP/1.1 2856Accept: text/plain 2857``` 2858 2859To parse the URL into its parts: 2860 2861```js 2862new URL(request.url, `http://${request.headers.host}`); 2863``` 2864 2865When `request.url` is `'/status?name=ryan'` and `request.headers.host` is 2866`'localhost:3000'`: 2867 2868```console 2869$ node 2870> new URL(request.url, `http://${request.headers.host}`) 2871URL { 2872 href: 'http://localhost:3000/status?name=ryan', 2873 origin: 'http://localhost:3000', 2874 protocol: 'http:', 2875 username: '', 2876 password: '', 2877 host: 'localhost:3000', 2878 hostname: 'localhost', 2879 port: '3000', 2880 pathname: '/status', 2881 search: '?name=ryan', 2882 searchParams: URLSearchParams { 'name' => 'ryan' }, 2883 hash: '' 2884} 2885``` 2886 2887## Class: `http.OutgoingMessage` 2888 2889<!-- YAML 2890added: v0.1.17 2891--> 2892 2893* Extends: {Stream} 2894 2895This class serves as the parent class of [`http.ClientRequest`][] 2896and [`http.ServerResponse`][]. It is an abstract outgoing message from 2897the perspective of the participants of an HTTP transaction. 2898 2899### Event: `'drain'` 2900 2901<!-- YAML 2902added: v0.3.6 2903--> 2904 2905Emitted when the buffer of the message is free again. 2906 2907### Event: `'finish'` 2908 2909<!-- YAML 2910added: v0.1.17 2911--> 2912 2913Emitted when the transmission is finished successfully. 2914 2915### Event: `'prefinish'` 2916 2917<!-- YAML 2918added: v0.11.6 2919--> 2920 2921Emitted after `outgoingMessage.end()` is called. 2922When the event is emitted, all data has been processed but not necessarily 2923completely flushed. 2924 2925### `outgoingMessage.addTrailers(headers)` 2926 2927<!-- YAML 2928added: v0.3.0 2929--> 2930 2931* `headers` {Object} 2932 2933Adds HTTP trailers (headers but at the end of the message) to the message. 2934 2935Trailers will **only** be emitted if the message is chunked encoded. If not, 2936the trailers will be silently discarded. 2937 2938HTTP requires the `Trailer` header to be sent to emit trailers, 2939with a list of header field names in its value, e.g. 2940 2941```js 2942message.writeHead(200, { 'Content-Type': 'text/plain', 2943 'Trailer': 'Content-MD5' }); 2944message.write(fileData); 2945message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); 2946message.end(); 2947``` 2948 2949Attempting to set a header field name or value that contains invalid characters 2950will result in a `TypeError` being thrown. 2951 2952### `outgoingMessage.appendHeader(name, value)` 2953 2954<!-- YAML 2955added: v18.3.0 2956--> 2957 2958* `name` {string} Header name 2959* `value` {string|string\[]} Header value 2960* Returns: {this} 2961 2962Append a single header value for the header object. 2963 2964If the value is an array, this is equivalent of calling this method multiple 2965times. 2966 2967If there were no previous value for the header, this is equivalent of calling 2968[`outgoingMessage.setHeader(name, value)`][]. 2969 2970Depending of the value of `options.uniqueHeaders` when the client request or the 2971server were created, this will end up in the header being sent multiple times or 2972a single time with values joined using `; `. 2973 2974### `outgoingMessage.connection` 2975 2976<!-- YAML 2977added: v0.3.0 2978deprecated: 2979 - v15.12.0 2980 - v14.17.1 2981--> 2982 2983> Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead. 2984 2985Alias of [`outgoingMessage.socket`][]. 2986 2987### `outgoingMessage.cork()` 2988 2989<!-- YAML 2990added: 2991 - v13.2.0 2992 - v12.16.0 2993--> 2994 2995See [`writable.cork()`][]. 2996 2997### `outgoingMessage.destroy([error])` 2998 2999<!-- YAML 3000added: v0.3.0 3001--> 3002 3003* `error` {Error} Optional, an error to emit with `error` event 3004* Returns: {this} 3005 3006Destroys the message. Once a socket is associated with the message 3007and is connected, that socket will be destroyed as well. 3008 3009### `outgoingMessage.end(chunk[, encoding][, callback])` 3010 3011<!-- YAML 3012added: v0.1.90 3013changes: 3014 - version: v15.0.0 3015 pr-url: https://github.com/nodejs/node/pull/33155 3016 description: The `chunk` parameter can now be a `Uint8Array`. 3017 - version: v0.11.6 3018 description: add `callback` argument. 3019--> 3020 3021* `chunk` {string|Buffer|Uint8Array} 3022* `encoding` {string} Optional, **Default**: `utf8` 3023* `callback` {Function} Optional 3024* Returns: {this} 3025 3026Finishes the outgoing message. If any parts of the body are unsent, it will 3027flush them to the underlying system. If the message is chunked, it will 3028send the terminating chunk `0\r\n\r\n`, and send the trailers (if any). 3029 3030If `chunk` is specified, it is equivalent to calling 3031`outgoingMessage.write(chunk, encoding)`, followed by 3032`outgoingMessage.end(callback)`. 3033 3034If `callback` is provided, it will be called when the message is finished 3035(equivalent to a listener of the `'finish'` event). 3036 3037### `outgoingMessage.flushHeaders()` 3038 3039<!-- YAML 3040added: v1.6.0 3041--> 3042 3043Flushes the message headers. 3044 3045For efficiency reason, Node.js normally buffers the message headers 3046until `outgoingMessage.end()` is called or the first chunk of message data 3047is written. It then tries to pack the headers and data into a single TCP 3048packet. 3049 3050It is usually desired (it saves a TCP round-trip), but not when the first 3051data is not sent until possibly much later. `outgoingMessage.flushHeaders()` 3052bypasses the optimization and kickstarts the message. 3053 3054### `outgoingMessage.getHeader(name)` 3055 3056<!-- YAML 3057added: v0.4.0 3058--> 3059 3060* `name` {string} Name of header 3061* Returns {string | undefined} 3062 3063Gets the value of the HTTP header with the given name. If that header is not 3064set, the returned value will be `undefined`. 3065 3066### `outgoingMessage.getHeaderNames()` 3067 3068<!-- YAML 3069added: v7.7.0 3070--> 3071 3072* Returns {string\[]} 3073 3074Returns an array containing the unique names of the current outgoing headers. 3075All names are lowercase. 3076 3077### `outgoingMessage.getHeaders()` 3078 3079<!-- YAML 3080added: v7.7.0 3081--> 3082 3083* Returns: {Object} 3084 3085Returns a shallow copy of the current outgoing headers. Since a shallow 3086copy is used, array values may be mutated without additional calls to 3087various header-related HTTP module methods. The keys of the returned 3088object are the header names and the values are the respective header 3089values. All header names are lowercase. 3090 3091The object returned by the `outgoingMessage.getHeaders()` method does 3092not prototypically inherit from the JavaScript `Object`. This means that 3093typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, 3094and others are not defined and will not work. 3095 3096```js 3097outgoingMessage.setHeader('Foo', 'bar'); 3098outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 3099 3100const headers = outgoingMessage.getHeaders(); 3101// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 3102``` 3103 3104### `outgoingMessage.hasHeader(name)` 3105 3106<!-- YAML 3107added: v7.7.0 3108--> 3109 3110* `name` {string} 3111* Returns {boolean} 3112 3113Returns `true` if the header identified by `name` is currently set in the 3114outgoing headers. The header name is case-insensitive. 3115 3116```js 3117const hasContentType = outgoingMessage.hasHeader('content-type'); 3118``` 3119 3120### `outgoingMessage.headersSent` 3121 3122<!-- YAML 3123added: v0.9.3 3124--> 3125 3126* {boolean} 3127 3128Read-only. `true` if the headers were sent, otherwise `false`. 3129 3130### `outgoingMessage.pipe()` 3131 3132<!-- YAML 3133added: v9.0.0 3134--> 3135 3136Overrides the `stream.pipe()` method inherited from the legacy `Stream` class 3137which is the parent class of `http.OutgoingMessage`. 3138 3139Calling this method will throw an `Error` because `outgoingMessage` is a 3140write-only stream. 3141 3142### `outgoingMessage.removeHeader(name)` 3143 3144<!-- YAML 3145added: v0.4.0 3146--> 3147 3148* `name` {string} Header name 3149 3150Removes a header that is queued for implicit sending. 3151 3152```js 3153outgoingMessage.removeHeader('Content-Encoding'); 3154``` 3155 3156### `outgoingMessage.setHeader(name, value)` 3157 3158<!-- YAML 3159added: v0.4.0 3160--> 3161 3162* `name` {string} Header name 3163* `value` {any} Header value 3164* Returns: {this} 3165 3166Sets a single header value. If the header already exists in the to-be-sent 3167headers, its value will be replaced. Use an array of strings to send multiple 3168headers with the same name. 3169 3170### `outgoingMessage.setHeaders(headers)` 3171 3172<!-- YAML 3173added: v18.15.0 3174--> 3175 3176* `headers` {Headers|Map} 3177* Returns: {http.ServerResponse} 3178 3179Returns the response object. 3180 3181Sets multiple header values for implicit headers. 3182`headers` must be an instance of [`Headers`][] or `Map`, 3183if a header already exists in the to-be-sent headers, 3184its value will be replaced. 3185 3186```js 3187const headers = new Headers({ foo: 'bar' }); 3188response.setHeaders(headers); 3189``` 3190 3191or 3192 3193```js 3194const headers = new Map([['foo', 'bar']]); 3195res.setHeaders(headers); 3196``` 3197 3198When headers have been set with [`outgoingMessage.setHeaders()`][], 3199they will be merged with any headers passed to [`response.writeHead()`][], 3200with the headers passed to [`response.writeHead()`][] given precedence. 3201 3202```js 3203// Returns content-type = text/plain 3204const server = http.createServer((req, res) => { 3205 const headers = new Headers({ 'Content-Type': 'text/html' }); 3206 res.setHeaders(headers); 3207 res.writeHead(200, { 'Content-Type': 'text/plain' }); 3208 res.end('ok'); 3209}); 3210``` 3211 3212### `outgoingMessage.setTimeout(msesc[, callback])` 3213 3214<!-- YAML 3215added: v0.9.12 3216--> 3217 3218* `msesc` {number} 3219* `callback` {Function} Optional function to be called when a timeout 3220 occurs. Same as binding to the `timeout` event. 3221* Returns: {this} 3222 3223Once a socket is associated with the message and is connected, 3224[`socket.setTimeout()`][] will be called with `msecs` as the first parameter. 3225 3226### `outgoingMessage.socket` 3227 3228<!-- YAML 3229added: v0.3.0 3230--> 3231 3232* {stream.Duplex} 3233 3234Reference to the underlying socket. Usually, users will not want to access 3235this property. 3236 3237After calling `outgoingMessage.end()`, this property will be nulled. 3238 3239### `outgoingMessage.uncork()` 3240 3241<!-- YAML 3242added: 3243 - v13.2.0 3244 - v12.16.0 3245--> 3246 3247See [`writable.uncork()`][] 3248 3249### `outgoingMessage.writableCorked` 3250 3251<!-- YAML 3252added: 3253 - v13.2.0 3254 - v12.16.0 3255--> 3256 3257* {number} 3258 3259The number of times `outgoingMessage.cork()` has been called. 3260 3261### `outgoingMessage.writableEnded` 3262 3263<!-- YAML 3264added: v12.9.0 3265--> 3266 3267* {boolean} 3268 3269Is `true` if `outgoingMessage.end()` has been called. This property does 3270not indicate whether the data has been flushed. For that purpose, use 3271`message.writableFinished` instead. 3272 3273### `outgoingMessage.writableFinished` 3274 3275<!-- YAML 3276added: v12.7.0 3277--> 3278 3279* {boolean} 3280 3281Is `true` if all data has been flushed to the underlying system. 3282 3283### `outgoingMessage.writableHighWaterMark` 3284 3285<!-- YAML 3286added: v12.9.0 3287--> 3288 3289* {number} 3290 3291The `highWaterMark` of the underlying socket if assigned. Otherwise, the default 3292buffer level when [`writable.write()`][] starts returning false (`16384`). 3293 3294### `outgoingMessage.writableLength` 3295 3296<!-- YAML 3297added: v12.9.0 3298--> 3299 3300* {number} 3301 3302The number of buffered bytes. 3303 3304### `outgoingMessage.writableObjectMode` 3305 3306<!-- YAML 3307added: v12.9.0 3308--> 3309 3310* {boolean} 3311 3312Always `false`. 3313 3314### `outgoingMessage.write(chunk[, encoding][, callback])` 3315 3316<!-- YAML 3317added: v0.1.29 3318changes: 3319 - version: v15.0.0 3320 pr-url: https://github.com/nodejs/node/pull/33155 3321 description: The `chunk` parameter can now be a `Uint8Array`. 3322 - version: v0.11.6 3323 description: The `callback` argument was added. 3324--> 3325 3326* `chunk` {string|Buffer|Uint8Array} 3327* `encoding` {string} **Default**: `utf8` 3328* `callback` {Function} 3329* Returns {boolean} 3330 3331Sends a chunk of the body. This method can be called multiple times. 3332 3333The `encoding` argument is only relevant when `chunk` is a string. Defaults to 3334`'utf8'`. 3335 3336The `callback` argument is optional and will be called when this chunk of data 3337is flushed. 3338 3339Returns `true` if the entire data was flushed successfully to the kernel 3340buffer. Returns `false` if all or part of the data was queued in the user 3341memory. The `'drain'` event will be emitted when the buffer is free again. 3342 3343## `http.METHODS` 3344 3345<!-- YAML 3346added: v0.11.8 3347--> 3348 3349* {string\[]} 3350 3351A list of the HTTP methods that are supported by the parser. 3352 3353## `http.STATUS_CODES` 3354 3355<!-- YAML 3356added: v0.1.22 3357--> 3358 3359* {Object} 3360 3361A collection of all the standard HTTP response status codes, and the 3362short description of each. For example, `http.STATUS_CODES[404] === 'Not 3363Found'`. 3364 3365## `http.createServer([options][, requestListener])` 3366 3367<!-- YAML 3368added: v0.1.13 3369changes: 3370 - version: v18.17.0 3371 pr-url: https://github.com/nodejs/node/pull/47405 3372 description: The `highWaterMark` option is supported now. 3373 - version: v18.0.0 3374 pr-url: https://github.com/nodejs/node/pull/41263 3375 description: The `requestTimeout`, `headersTimeout`, `keepAliveTimeout`, and 3376 `connectionsCheckingInterval` options are supported now. 3377 - version: v18.0.0 3378 pr-url: https://github.com/nodejs/node/pull/42163 3379 description: The `noDelay` option now defaults to `true`. 3380 - version: v17.7.0 3381 pr-url: https://github.com/nodejs/node/pull/41310 3382 description: The `noDelay`, `keepAlive` and `keepAliveInitialDelay` 3383 options are supported now. 3384 - version: 3385 - v13.8.0 3386 - v12.15.0 3387 - v10.19.0 3388 pr-url: https://github.com/nodejs/node/pull/31448 3389 description: The `insecureHTTPParser` option is supported now. 3390 - version: v13.3.0 3391 pr-url: https://github.com/nodejs/node/pull/30570 3392 description: The `maxHeaderSize` option is supported now. 3393 - version: 3394 - v9.6.0 3395 - v8.12.0 3396 pr-url: https://github.com/nodejs/node/pull/15752 3397 description: The `options` argument is supported now. 3398--> 3399 3400* `options` {Object} 3401 * `connectionsCheckingInterval`: Sets the interval value in milliseconds to 3402 check for request and headers timeout in incomplete requests. 3403 **Default:** `30000`. 3404 * `headersTimeout`: Sets the timeout value in milliseconds for receiving 3405 the complete HTTP headers from the client. 3406 See [`server.headersTimeout`][] for more information. 3407 **Default:** `60000`. 3408 * `highWaterMark` {number} Optionally overrides all `socket`s' 3409 `readableHighWaterMark` and `writableHighWaterMark`. This affects 3410 `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. 3411 **Default:** See [`stream.getDefaultHighWaterMark()`][]. 3412 * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts 3413 invalid HTTP headers when `true`. Using the insecure parser should be 3414 avoided. See [`--insecure-http-parser`][] for more information. 3415 **Default:** `false`. 3416 * `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` 3417 class to be used. Useful for extending the original `IncomingMessage`. 3418 **Default:** `IncomingMessage`. 3419 * `joinDuplicateHeaders` {boolean} It joins the field line values of multiple 3420 headers in a request with `, ` instead of discarding the duplicates. 3421 See [`message.headers`][] for more information. 3422 **Default:** `false`. 3423 * `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality 3424 on the socket immediately after a new incoming connection is received, 3425 similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`]. 3426 **Default:** `false`. 3427 * `keepAliveInitialDelay` {number} If set to a positive number, it sets the 3428 initial delay before the first keepalive probe is sent on an idle socket. 3429 **Default:** `0`. 3430 * `requestTimeout`: Sets the timeout value in milliseconds for receiving 3431 the entire request from the client. 3432 See [`server.requestTimeout`][] for more information. 3433 **Default:** `300000`. 3434 * `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class 3435 to be used. Useful for extending the original `ServerResponse`. **Default:** 3436 `ServerResponse`. 3437 * `uniqueHeaders` {Array} A list of response headers that should be sent only 3438 once. If the header's value is an array, the items will be joined 3439 using `; `. 3440 3441* `requestListener` {Function} 3442 3443* Returns: {http.Server} 3444 3445Returns a new instance of [`http.Server`][]. 3446 3447The `requestListener` is a function which is automatically 3448added to the [`'request'`][] event. 3449 3450```mjs 3451import http from 'node:http'; 3452 3453// Create a local server to receive data from 3454const server = http.createServer((req, res) => { 3455 res.writeHead(200, { 'Content-Type': 'application/json' }); 3456 res.end(JSON.stringify({ 3457 data: 'Hello World!', 3458 })); 3459}); 3460 3461server.listen(8000); 3462``` 3463 3464```cjs 3465const http = require('node:http'); 3466 3467// Create a local server to receive data from 3468const server = http.createServer((req, res) => { 3469 res.writeHead(200, { 'Content-Type': 'application/json' }); 3470 res.end(JSON.stringify({ 3471 data: 'Hello World!', 3472 })); 3473}); 3474 3475server.listen(8000); 3476``` 3477 3478```mjs 3479import http from 'node:http'; 3480 3481// Create a local server to receive data from 3482const server = http.createServer(); 3483 3484// Listen to the request event 3485server.on('request', (request, res) => { 3486 res.writeHead(200, { 'Content-Type': 'application/json' }); 3487 res.end(JSON.stringify({ 3488 data: 'Hello World!', 3489 })); 3490}); 3491 3492server.listen(8000); 3493``` 3494 3495```cjs 3496const http = require('node:http'); 3497 3498// Create a local server to receive data from 3499const server = http.createServer(); 3500 3501// Listen to the request event 3502server.on('request', (request, res) => { 3503 res.writeHead(200, { 'Content-Type': 'application/json' }); 3504 res.end(JSON.stringify({ 3505 data: 'Hello World!', 3506 })); 3507}); 3508 3509server.listen(8000); 3510``` 3511 3512## `http.get(options[, callback])` 3513 3514## `http.get(url[, options][, callback])` 3515 3516<!-- YAML 3517added: v0.3.6 3518changes: 3519 - version: v10.9.0 3520 pr-url: https://github.com/nodejs/node/pull/21616 3521 description: The `url` parameter can now be passed along with a separate 3522 `options` object. 3523 - version: v7.5.0 3524 pr-url: https://github.com/nodejs/node/pull/10638 3525 description: The `options` parameter can be a WHATWG `URL` object. 3526--> 3527 3528* `url` {string | URL} 3529* `options` {Object} Accepts the same `options` as 3530 [`http.request()`][], with the method set to GET by default. 3531* `callback` {Function} 3532* Returns: {http.ClientRequest} 3533 3534Since most requests are GET requests without bodies, Node.js provides this 3535convenience method. The only difference between this method and 3536[`http.request()`][] is that it sets the method to GET by default and calls `req.end()` 3537automatically. The callback must take care to consume the response 3538data for reasons stated in [`http.ClientRequest`][] section. 3539 3540The `callback` is invoked with a single argument that is an instance of 3541[`http.IncomingMessage`][]. 3542 3543JSON fetching example: 3544 3545```js 3546http.get('http://localhost:8000/', (res) => { 3547 const { statusCode } = res; 3548 const contentType = res.headers['content-type']; 3549 3550 let error; 3551 // Any 2xx status code signals a successful response but 3552 // here we're only checking for 200. 3553 if (statusCode !== 200) { 3554 error = new Error('Request Failed.\n' + 3555 `Status Code: ${statusCode}`); 3556 } else if (!/^application\/json/.test(contentType)) { 3557 error = new Error('Invalid content-type.\n' + 3558 `Expected application/json but received ${contentType}`); 3559 } 3560 if (error) { 3561 console.error(error.message); 3562 // Consume response data to free up memory 3563 res.resume(); 3564 return; 3565 } 3566 3567 res.setEncoding('utf8'); 3568 let rawData = ''; 3569 res.on('data', (chunk) => { rawData += chunk; }); 3570 res.on('end', () => { 3571 try { 3572 const parsedData = JSON.parse(rawData); 3573 console.log(parsedData); 3574 } catch (e) { 3575 console.error(e.message); 3576 } 3577 }); 3578}).on('error', (e) => { 3579 console.error(`Got error: ${e.message}`); 3580}); 3581 3582// Create a local server to receive data from 3583const server = http.createServer((req, res) => { 3584 res.writeHead(200, { 'Content-Type': 'application/json' }); 3585 res.end(JSON.stringify({ 3586 data: 'Hello World!', 3587 })); 3588}); 3589 3590server.listen(8000); 3591``` 3592 3593## `http.globalAgent` 3594 3595<!-- YAML 3596added: v0.5.9 3597--> 3598 3599* {http.Agent} 3600 3601Global instance of `Agent` which is used as the default for all HTTP client 3602requests. 3603 3604## `http.maxHeaderSize` 3605 3606<!-- YAML 3607added: 3608 - v11.6.0 3609 - v10.15.0 3610--> 3611 3612* {number} 3613 3614Read-only property specifying the maximum allowed size of HTTP headers in bytes. 3615Defaults to 16 KiB. Configurable using the [`--max-http-header-size`][] CLI 3616option. 3617 3618This can be overridden for servers and client requests by passing the 3619`maxHeaderSize` option. 3620 3621## `http.request(options[, callback])` 3622 3623## `http.request(url[, options][, callback])` 3624 3625<!-- YAML 3626added: v0.3.6 3627changes: 3628 - version: 3629 - v16.7.0 3630 - v14.18.0 3631 pr-url: https://github.com/nodejs/node/pull/39310 3632 description: When using a `URL` object parsed username and 3633 password will now be properly URI decoded. 3634 - version: 3635 - v15.3.0 3636 - v14.17.0 3637 pr-url: https://github.com/nodejs/node/pull/36048 3638 description: It is possible to abort a request with an AbortSignal. 3639 - version: 3640 - v13.8.0 3641 - v12.15.0 3642 - v10.19.0 3643 pr-url: https://github.com/nodejs/node/pull/31448 3644 description: The `insecureHTTPParser` option is supported now. 3645 - version: v13.3.0 3646 pr-url: https://github.com/nodejs/node/pull/30570 3647 description: The `maxHeaderSize` option is supported now. 3648 - version: v10.9.0 3649 pr-url: https://github.com/nodejs/node/pull/21616 3650 description: The `url` parameter can now be passed along with a separate 3651 `options` object. 3652 - version: v7.5.0 3653 pr-url: https://github.com/nodejs/node/pull/10638 3654 description: The `options` parameter can be a WHATWG `URL` object. 3655--> 3656 3657* `url` {string | URL} 3658* `options` {Object} 3659 * `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible 3660 values: 3661 * `undefined` (default): use [`http.globalAgent`][] for this host and port. 3662 * `Agent` object: explicitly use the passed in `Agent`. 3663 * `false`: causes a new `Agent` with default values to be used. 3664 * `auth` {string} Basic authentication (`'user:password'`) to compute an 3665 Authorization header. 3666 * `createConnection` {Function} A function that produces a socket/stream to 3667 use for the request when the `agent` option is not used. This can be used to 3668 avoid creating a custom `Agent` class just to override the default 3669 `createConnection` function. See [`agent.createConnection()`][] for more 3670 details. Any [`Duplex`][] stream is a valid return value. 3671 * `defaultPort` {number} Default port for the protocol. **Default:** 3672 `agent.defaultPort` if an `Agent` is used, else `undefined`. 3673 * `family` {number} IP address family to use when resolving `host` or 3674 `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and 3675 v6 will be used. 3676 * `headers` {Object} An object containing request headers. 3677 * `hints` {number} Optional [`dns.lookup()` hints][]. 3678 * `host` {string} A domain name or IP address of the server to issue the 3679 request to. **Default:** `'localhost'`. 3680 * `hostname` {string} Alias for `host`. To support [`url.parse()`][], 3681 `hostname` will be used if both `host` and `hostname` are specified. 3682 * `insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts 3683 invalid HTTP headers when `true`. Using the insecure parser should be 3684 avoided. See [`--insecure-http-parser`][] for more information. 3685 **Default:** `false` 3686 * `joinDuplicateHeaders` {boolean} It joins the field line values of 3687 multiple headers in a request with `, ` instead of discarding 3688 the duplicates. See [`message.headers`][] for more information. 3689 **Default:** `false`. 3690 * `localAddress` {string} Local interface to bind for network connections. 3691 * `localPort` {number} Local port to connect from. 3692 * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][]. 3693 * `maxHeaderSize` {number} Optionally overrides the value of 3694 [`--max-http-header-size`][] (the maximum length of response headers in 3695 bytes) for responses received from the server. 3696 **Default:** 16384 (16 KiB). 3697 * `method` {string} A string specifying the HTTP request method. **Default:** 3698 `'GET'`. 3699 * `path` {string} Request path. Should include query string if any. 3700 E.G. `'/index.html?page=12'`. An exception is thrown when the request path 3701 contains illegal characters. Currently, only spaces are rejected but that 3702 may change in the future. **Default:** `'/'`. 3703 * `port` {number} Port of remote server. **Default:** `defaultPort` if set, 3704 else `80`. 3705 * `protocol` {string} Protocol to use. **Default:** `'http:'`. 3706 * `setHost` {boolean}: Specifies whether or not to automatically add the 3707 `Host` header. Defaults to `true`. 3708 * `signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing 3709 request. 3710 * `socketPath` {string} Unix domain socket. Cannot be used if one of `host` 3711 or `port` is specified, as those specify a TCP Socket. 3712 * `timeout` {number}: A number specifying the socket timeout in milliseconds. 3713 This will set the timeout before the socket is connected. 3714 * `uniqueHeaders` {Array} A list of request headers that should be sent 3715 only once. If the header's value is an array, the items will be joined 3716 using `; `. 3717* `callback` {Function} 3718* Returns: {http.ClientRequest} 3719 3720`options` in [`socket.connect()`][] are also supported. 3721 3722Node.js maintains several connections per server to make HTTP requests. 3723This function allows one to transparently issue requests. 3724 3725`url` can be a string or a [`URL`][] object. If `url` is a 3726string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][] 3727object, it will be automatically converted to an ordinary `options` object. 3728 3729If both `url` and `options` are specified, the objects are merged, with the 3730`options` properties taking precedence. 3731 3732The optional `callback` parameter will be added as a one-time listener for 3733the [`'response'`][] event. 3734 3735`http.request()` returns an instance of the [`http.ClientRequest`][] 3736class. The `ClientRequest` instance is a writable stream. If one needs to 3737upload a file with a POST request, then write to the `ClientRequest` object. 3738 3739```mjs 3740import http from 'node:http'; 3741import { Buffer } from 'node:buffer'; 3742 3743const postData = JSON.stringify({ 3744 'msg': 'Hello World!', 3745}); 3746 3747const options = { 3748 hostname: 'www.google.com', 3749 port: 80, 3750 path: '/upload', 3751 method: 'POST', 3752 headers: { 3753 'Content-Type': 'application/json', 3754 'Content-Length': Buffer.byteLength(postData), 3755 }, 3756}; 3757 3758const req = http.request(options, (res) => { 3759 console.log(`STATUS: ${res.statusCode}`); 3760 console.log(`HEADERS: ${JSON.stringify(res.headers)}`); 3761 res.setEncoding('utf8'); 3762 res.on('data', (chunk) => { 3763 console.log(`BODY: ${chunk}`); 3764 }); 3765 res.on('end', () => { 3766 console.log('No more data in response.'); 3767 }); 3768}); 3769 3770req.on('error', (e) => { 3771 console.error(`problem with request: ${e.message}`); 3772}); 3773 3774// Write data to request body 3775req.write(postData); 3776req.end(); 3777``` 3778 3779```cjs 3780const http = require('node:http'); 3781 3782const postData = JSON.stringify({ 3783 'msg': 'Hello World!', 3784}); 3785 3786const options = { 3787 hostname: 'www.google.com', 3788 port: 80, 3789 path: '/upload', 3790 method: 'POST', 3791 headers: { 3792 'Content-Type': 'application/json', 3793 'Content-Length': Buffer.byteLength(postData), 3794 }, 3795}; 3796 3797const req = http.request(options, (res) => { 3798 console.log(`STATUS: ${res.statusCode}`); 3799 console.log(`HEADERS: ${JSON.stringify(res.headers)}`); 3800 res.setEncoding('utf8'); 3801 res.on('data', (chunk) => { 3802 console.log(`BODY: ${chunk}`); 3803 }); 3804 res.on('end', () => { 3805 console.log('No more data in response.'); 3806 }); 3807}); 3808 3809req.on('error', (e) => { 3810 console.error(`problem with request: ${e.message}`); 3811}); 3812 3813// Write data to request body 3814req.write(postData); 3815req.end(); 3816``` 3817 3818In the example `req.end()` was called. With `http.request()` one 3819must always call `req.end()` to signify the end of the request - 3820even if there is no data being written to the request body. 3821 3822If any error is encountered during the request (be that with DNS resolution, 3823TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted 3824on the returned request object. As with all `'error'` events, if no listeners 3825are registered the error will be thrown. 3826 3827There are a few special headers that should be noted. 3828 3829* Sending a 'Connection: keep-alive' will notify Node.js that the connection to 3830 the server should be persisted until the next request. 3831 3832* Sending a 'Content-Length' header will disable the default chunked encoding. 3833 3834* Sending an 'Expect' header will immediately send the request headers. 3835 Usually, when sending 'Expect: 100-continue', both a timeout and a listener 3836 for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more 3837 information. 3838 3839* Sending an Authorization header will override using the `auth` option 3840 to compute basic authentication. 3841 3842Example using a [`URL`][] as `options`: 3843 3844```js 3845const options = new URL('http://abc:xyz@example.com'); 3846 3847const req = http.request(options, (res) => { 3848 // ... 3849}); 3850``` 3851 3852In a successful request, the following events will be emitted in the following 3853order: 3854 3855* `'socket'` 3856* `'response'` 3857 * `'data'` any number of times, on the `res` object 3858 (`'data'` will not be emitted at all if the response body is empty, for 3859 instance, in most redirects) 3860 * `'end'` on the `res` object 3861* `'close'` 3862 3863In the case of a connection error, the following events will be emitted: 3864 3865* `'socket'` 3866* `'error'` 3867* `'close'` 3868 3869In the case of a premature connection close before the response is received, 3870the following events will be emitted in the following order: 3871 3872* `'socket'` 3873* `'error'` with an error with message `'Error: socket hang up'` and code 3874 `'ECONNRESET'` 3875* `'close'` 3876 3877In the case of a premature connection close after the response is received, 3878the following events will be emitted in the following order: 3879 3880* `'socket'` 3881* `'response'` 3882 * `'data'` any number of times, on the `res` object 3883* (connection closed here) 3884* `'aborted'` on the `res` object 3885* `'error'` on the `res` object with an error with message 3886 `'Error: aborted'` and code `'ECONNRESET'` 3887* `'close'` 3888* `'close'` on the `res` object 3889 3890If `req.destroy()` is called before a socket is assigned, the following 3891events will be emitted in the following order: 3892 3893* (`req.destroy()` called here) 3894* `'error'` with an error with message `'Error: socket hang up'` and code 3895 `'ECONNRESET'`, or the error with which `req.destroy()` was called 3896* `'close'` 3897 3898If `req.destroy()` is called before the connection succeeds, the following 3899events will be emitted in the following order: 3900 3901* `'socket'` 3902* (`req.destroy()` called here) 3903* `'error'` with an error with message `'Error: socket hang up'` and code 3904 `'ECONNRESET'`, or the error with which `req.destroy()` was called 3905* `'close'` 3906 3907If `req.destroy()` is called after the response is received, the following 3908events will be emitted in the following order: 3909 3910* `'socket'` 3911* `'response'` 3912 * `'data'` any number of times, on the `res` object 3913* (`req.destroy()` called here) 3914* `'aborted'` on the `res` object 3915* `'error'` on the `res` object with an error with message `'Error: aborted'` 3916 and code `'ECONNRESET'`, or the error with which `req.destroy()` was called 3917* `'close'` 3918* `'close'` on the `res` object 3919 3920If `req.abort()` is called before a socket is assigned, the following 3921events will be emitted in the following order: 3922 3923* (`req.abort()` called here) 3924* `'abort'` 3925* `'close'` 3926 3927If `req.abort()` is called before the connection succeeds, the following 3928events will be emitted in the following order: 3929 3930* `'socket'` 3931* (`req.abort()` called here) 3932* `'abort'` 3933* `'error'` with an error with message `'Error: socket hang up'` and code 3934 `'ECONNRESET'` 3935* `'close'` 3936 3937If `req.abort()` is called after the response is received, the following 3938events will be emitted in the following order: 3939 3940* `'socket'` 3941* `'response'` 3942 * `'data'` any number of times, on the `res` object 3943* (`req.abort()` called here) 3944* `'abort'` 3945* `'aborted'` on the `res` object 3946* `'error'` on the `res` object with an error with message 3947 `'Error: aborted'` and code `'ECONNRESET'`. 3948* `'close'` 3949* `'close'` on the `res` object 3950 3951Setting the `timeout` option or using the `setTimeout()` function will 3952not abort the request or do anything besides add a `'timeout'` event. 3953 3954Passing an `AbortSignal` and then calling `abort()` on the corresponding 3955`AbortController` will behave the same way as calling `.destroy()` on the 3956request. Specifically, the `'error'` event will be emitted with an error with 3957the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` 3958and the `cause`, if one was provided. 3959 3960## `http.validateHeaderName(name[, label])` 3961 3962<!-- YAML 3963added: v14.3.0 3964changes: 3965 - version: v18.14.0 3966 pr-url: https://github.com/nodejs/node/pull/46143 3967 description: The `label` parameter is added. 3968--> 3969 3970* `name` {string} 3971* `label` {string} Label for error message. **Default:** `'Header name'`. 3972 3973Performs the low-level validations on the provided `name` that are done when 3974`res.setHeader(name, value)` is called. 3975 3976Passing illegal value as `name` will result in a [`TypeError`][] being thrown, 3977identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. 3978 3979It is not necessary to use this method before passing headers to an HTTP request 3980or response. The HTTP module will automatically validate such headers. 3981Examples: 3982 3983Example: 3984 3985```mjs 3986import { validateHeaderName } from 'node:http'; 3987 3988try { 3989 validateHeaderName(''); 3990} catch (err) { 3991 console.error(err instanceof TypeError); // --> true 3992 console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' 3993 console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' 3994} 3995``` 3996 3997```cjs 3998const { validateHeaderName } = require('node:http'); 3999 4000try { 4001 validateHeaderName(''); 4002} catch (err) { 4003 console.error(err instanceof TypeError); // --> true 4004 console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' 4005 console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' 4006} 4007``` 4008 4009## `http.validateHeaderValue(name, value)` 4010 4011<!-- YAML 4012added: v14.3.0 4013--> 4014 4015* `name` {string} 4016* `value` {any} 4017 4018Performs the low-level validations on the provided `value` that are done when 4019`res.setHeader(name, value)` is called. 4020 4021Passing illegal value as `value` will result in a [`TypeError`][] being thrown. 4022 4023* Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. 4024* Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. 4025 4026It is not necessary to use this method before passing headers to an HTTP request 4027or response. The HTTP module will automatically validate such headers. 4028 4029Examples: 4030 4031```mjs 4032import { validateHeaderValue } from 'node:http'; 4033 4034try { 4035 validateHeaderValue('x-my-header', undefined); 4036} catch (err) { 4037 console.error(err instanceof TypeError); // --> true 4038 console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true 4039 console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' 4040} 4041 4042try { 4043 validateHeaderValue('x-my-header', 'oʊmɪɡə'); 4044} catch (err) { 4045 console.error(err instanceof TypeError); // --> true 4046 console.error(err.code === 'ERR_INVALID_CHAR'); // --> true 4047 console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' 4048} 4049``` 4050 4051```cjs 4052const { validateHeaderValue } = require('node:http'); 4053 4054try { 4055 validateHeaderValue('x-my-header', undefined); 4056} catch (err) { 4057 console.error(err instanceof TypeError); // --> true 4058 console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true 4059 console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' 4060} 4061 4062try { 4063 validateHeaderValue('x-my-header', 'oʊmɪɡə'); 4064} catch (err) { 4065 console.error(err instanceof TypeError); // --> true 4066 console.error(err.code === 'ERR_INVALID_CHAR'); // --> true 4067 console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' 4068} 4069``` 4070 4071## `http.setMaxIdleHTTPParsers(max)` 4072 4073<!-- YAML 4074added: v18.8.0 4075--> 4076 4077* `max` {number} **Default:** `1000`. 4078 4079Set the maximum number of idle HTTP parsers. 4080 4081[RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt 4082[`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`]: errors.md#err_http_content_length_mismatch 4083[`'checkContinue'`]: #event-checkcontinue 4084[`'finish'`]: #event-finish 4085[`'request'`]: #event-request 4086[`'response'`]: #event-response 4087[`'upgrade'`]: #event-upgrade 4088[`--insecure-http-parser`]: cli.md#--insecure-http-parser 4089[`--max-http-header-size`]: cli.md#--max-http-header-sizesize 4090[`Agent`]: #class-httpagent 4091[`Buffer.byteLength()`]: buffer.md#static-method-bufferbytelengthstring-encoding 4092[`Duplex`]: stream.md#class-streamduplex 4093[`HPE_HEADER_OVERFLOW`]: errors.md#hpe_header_overflow 4094[`Headers`]: globals.md#class-headers 4095[`TypeError`]: errors.md#class-typeerror 4096[`URL`]: url.md#the-whatwg-url-api 4097[`agent.createConnection()`]: #agentcreateconnectionoptions-callback 4098[`agent.getName()`]: #agentgetnameoptions 4099[`destroy()`]: #agentdestroy 4100[`dns.lookup()`]: dns.md#dnslookuphostname-options-callback 4101[`dns.lookup()` hints]: dns.md#supported-getaddrinfo-flags 4102[`getHeader(name)`]: #requestgetheadername 4103[`http.Agent`]: #class-httpagent 4104[`http.ClientRequest`]: #class-httpclientrequest 4105[`http.IncomingMessage`]: #class-httpincomingmessage 4106[`http.ServerResponse`]: #class-httpserverresponse 4107[`http.Server`]: #class-httpserver 4108[`http.createServer()`]: #httpcreateserveroptions-requestlistener 4109[`http.get()`]: #httpgetoptions-callback 4110[`http.globalAgent`]: #httpglobalagent 4111[`http.request()`]: #httprequestoptions-callback 4112[`message.headers`]: #messageheaders 4113[`message.socket`]: #messagesocket 4114[`message.trailers`]: #messagetrailers 4115[`net.Server.close()`]: net.md#serverclosecallback 4116[`net.Server`]: net.md#class-netserver 4117[`net.Socket`]: net.md#class-netsocket 4118[`net.createConnection()`]: net.md#netcreateconnectionoptions-connectlistener 4119[`new URL()`]: url.md#new-urlinput-base 4120[`outgoingMessage.setHeader(name, value)`]: #outgoingmessagesetheadername-value 4121[`outgoingMessage.setHeaders()`]: #outgoingmessagesetheadersheaders 4122[`outgoingMessage.socket`]: #outgoingmessagesocket 4123[`removeHeader(name)`]: #requestremoveheadername 4124[`request.destroy()`]: #requestdestroyerror 4125[`request.destroyed`]: #requestdestroyed 4126[`request.end()`]: #requestenddata-encoding-callback 4127[`request.flushHeaders()`]: #requestflushheaders 4128[`request.getHeader()`]: #requestgetheadername 4129[`request.setHeader()`]: #requestsetheadername-value 4130[`request.setTimeout()`]: #requestsettimeouttimeout-callback 4131[`request.socket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed 4132[`request.socket`]: #requestsocket 4133[`request.writableEnded`]: #requestwritableended 4134[`request.writableFinished`]: #requestwritablefinished 4135[`request.write(data, encoding)`]: #requestwritechunk-encoding-callback 4136[`response.end()`]: #responseenddata-encoding-callback 4137[`response.getHeader()`]: #responsegetheadername 4138[`response.setHeader()`]: #responsesetheadername-value 4139[`response.socket`]: #responsesocket 4140[`response.strictContentLength`]: #responsestrictcontentlength 4141[`response.writableEnded`]: #responsewritableended 4142[`response.writableFinished`]: #responsewritablefinished 4143[`response.write()`]: #responsewritechunk-encoding-callback 4144[`response.write(data, encoding)`]: #responsewritechunk-encoding-callback 4145[`response.writeContinue()`]: #responsewritecontinue 4146[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers 4147[`server.headersTimeout`]: #serverheaderstimeout 4148[`server.listen()`]: net.md#serverlisten 4149[`server.requestTimeout`]: #serverrequesttimeout 4150[`server.timeout`]: #servertimeout 4151[`setHeader(name, value)`]: #requestsetheadername-value 4152[`socket.connect()`]: net.md#socketconnectoptions-connectlistener 4153[`socket.setKeepAlive()`]: net.md#socketsetkeepaliveenable-initialdelay 4154[`socket.setNoDelay()`]: net.md#socketsetnodelaynodelay 4155[`socket.setTimeout()`]: net.md#socketsettimeouttimeout-callback 4156[`socket.unref()`]: net.md#socketunref 4157[`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode 4158[`url.parse()`]: url.md#urlparseurlstring-parsequerystring-slashesdenotehost 4159[`writable.cork()`]: stream.md#writablecork 4160[`writable.destroy()`]: stream.md#writabledestroyerror 4161[`writable.destroyed`]: stream.md#writabledestroyed 4162[`writable.uncork()`]: stream.md#writableuncork 4163[`writable.write()`]: stream.md#writablewritechunk-encoding-callback 4164[initial delay]: net.md#socketsetkeepaliveenable-initialdelay 4165