CINXE.COM
HTTP | Node.js v14.21.3 Documentation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v14.21.3"> <title>HTTP | Node.js v14.21.3 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <link rel="canonical" href="https://nodejs.org/api/http.html"> </head> <body class="alt apidoc" id="api-section-http"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http active">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="policy.html" class="nav-policy">Policies</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="http" class="interior"> <header> <div class="header-container"> <h1>Node.js v14.21.3 documentation</h1> <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> <path fill="none" d="M0 0h24v24H0z" /> <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/> <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> <path d="M0 0h24v24H0z" fill="none" /> <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> </svg> </button> </div> <div id="gtoc"> <ul> <li> <a href="index.html">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="http.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v19.x/api/http.html">19.x</a></li> <li><a href="https://nodejs.org/docs/latest-v18.x/api/http.html">18.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v17.x/api/http.html">17.x</a></li> <li><a href="https://nodejs.org/docs/latest-v16.x/api/http.html">16.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v15.x/api/http.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/http.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/http.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/http.html">12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/http.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/http.html">10.x</a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/http.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/http.html">8.x</a></li> <li><a href="https://nodejs.org/docs/latest-v7.x/api/http.html">7.x</a></li> <li><a href="https://nodejs.org/docs/latest-v6.x/api/http.html">6.x</a></li> <li><a href="https://nodejs.org/docs/latest-v5.x/api/http.html">5.x</a></li> <li><a href="https://nodejs.org/docs/latest-v4.x/api/http.html">4.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.12.x/api/http.html">0.12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.10.x/api/http.html">0.10.x</a></li></ol> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/http.md">Edit on GitHub</a></li> </ul> </div> <hr> </header> <details id="toc" open><summary>Table of contents</summary><ul> <li><span class="stability_2"><a href="#http_http">HTTP</a></span> <ul> <li><a href="#http_class_http_agent">Class: <code>http.Agent</code></a> <ul> <li><a href="#http_new_agent_options"><code>new Agent([options])</code></a></li> <li><a href="#http_agent_createconnection_options_callback"><code>agent.createConnection(options[, callback])</code></a></li> <li><a href="#http_agent_keepsocketalive_socket"><code>agent.keepSocketAlive(socket)</code></a></li> <li><a href="#http_agent_reusesocket_socket_request"><code>agent.reuseSocket(socket, request)</code></a></li> <li><a href="#http_agent_destroy"><code>agent.destroy()</code></a></li> <li><a href="#http_agent_freesockets"><code>agent.freeSockets</code></a></li> <li><a href="#http_agent_getname_options"><code>agent.getName(options)</code></a></li> <li><a href="#http_agent_maxfreesockets"><code>agent.maxFreeSockets</code></a></li> <li><a href="#http_agent_maxsockets"><code>agent.maxSockets</code></a></li> <li><a href="#http_agent_maxtotalsockets"><code>agent.maxTotalSockets</code></a></li> <li><a href="#http_agent_requests"><code>agent.requests</code></a></li> <li><a href="#http_agent_sockets"><code>agent.sockets</code></a></li> </ul> </li> <li><a href="#http_class_http_clientrequest">Class: <code>http.ClientRequest</code></a> <ul> <li><a href="#http_event_abort">Event: <code>'abort'</code></a></li> <li><a href="#http_event_connect">Event: <code>'connect'</code></a></li> <li><a href="#http_event_continue">Event: <code>'continue'</code></a></li> <li><a href="#http_event_information">Event: <code>'information'</code></a></li> <li><a href="#http_event_response">Event: <code>'response'</code></a></li> <li><a href="#http_event_socket">Event: <code>'socket'</code></a></li> <li><a href="#http_event_timeout">Event: <code>'timeout'</code></a></li> <li><a href="#http_event_upgrade">Event: <code>'upgrade'</code></a></li> <li><span class="stability_0"><a href="#http_request_abort"><code>request.abort()</code></a></span></li> <li><a href="#http_request_aborted"><code>request.aborted</code></a></li> <li><span class="stability_0"><a href="#http_request_connection"><code>request.connection</code></a></span></li> <li><a href="#http_request_end_data_encoding_callback"><code>request.end([data[, encoding]][, callback])</code></a></li> <li><a href="#http_request_destroy_error"><code>request.destroy([error])</code></a> <ul> <li><a href="#http_request_destroyed"><code>request.destroyed</code></a></li> </ul> </li> <li><span class="stability_0"><a href="#http_request_finished"><code>request.finished</code></a></span></li> <li><a href="#http_request_flushheaders"><code>request.flushHeaders()</code></a></li> <li><a href="#http_request_getheader_name"><code>request.getHeader(name)</code></a></li> <li><a href="#http_request_getrawheadernames"><code>request.getRawHeaderNames()</code></a></li> <li><a href="#http_request_maxheaderscount"><code>request.maxHeadersCount</code></a></li> <li><a href="#http_request_path"><code>request.path</code></a></li> <li><a href="#http_request_method"><code>request.method</code></a></li> <li><a href="#http_request_host"><code>request.host</code></a></li> <li><a href="#http_request_protocol"><code>request.protocol</code></a></li> <li><a href="#http_request_removeheader_name"><code>request.removeHeader(name)</code></a></li> <li><a href="#http_request_reusedsocket"><code>request.reusedSocket</code></a></li> <li><a href="#http_request_setheader_name_value"><code>request.setHeader(name, value)</code></a></li> <li><a href="#http_request_setnodelay_nodelay"><code>request.setNoDelay([noDelay])</code></a></li> <li><a href="#http_request_setsocketkeepalive_enable_initialdelay"><code>request.setSocketKeepAlive([enable][, initialDelay])</code></a></li> <li><a href="#http_request_settimeout_timeout_callback"><code>request.setTimeout(timeout[, callback])</code></a></li> <li><a href="#http_request_socket"><code>request.socket</code></a></li> <li><a href="#http_request_writableended"><code>request.writableEnded</code></a></li> <li><a href="#http_request_writablefinished"><code>request.writableFinished</code></a></li> <li><a href="#http_request_write_chunk_encoding_callback"><code>request.write(chunk[, encoding][, callback])</code></a></li> </ul> </li> <li><a href="#http_class_http_server">Class: <code>http.Server</code></a> <ul> <li><a href="#http_event_checkcontinue">Event: <code>'checkContinue'</code></a></li> <li><a href="#http_event_checkexpectation">Event: <code>'checkExpectation'</code></a></li> <li><a href="#http_event_clienterror">Event: <code>'clientError'</code></a></li> <li><a href="#http_event_close">Event: <code>'close'</code></a></li> <li><a href="#http_event_connect_1">Event: <code>'connect'</code></a></li> <li><a href="#http_event_connection">Event: <code>'connection'</code></a></li> <li><a href="#http_event_request">Event: <code>'request'</code></a></li> <li><a href="#http_event_upgrade_1">Event: <code>'upgrade'</code></a></li> <li><a href="#http_server_close_callback"><code>server.close([callback])</code></a></li> <li><a href="#http_server_headerstimeout"><code>server.headersTimeout</code></a></li> <li><a href="#http_server_listen"><code>server.listen()</code></a></li> <li><a href="#http_server_listening"><code>server.listening</code></a></li> <li><a href="#http_server_maxheaderscount"><code>server.maxHeadersCount</code></a></li> <li><a href="#http_server_requesttimeout"><code>server.requestTimeout</code></a></li> <li><a href="#http_server_settimeout_msecs_callback"><code>server.setTimeout([msecs][, callback])</code></a></li> <li><a href="#http_server_timeout"><code>server.timeout</code></a></li> <li><a href="#http_server_keepalivetimeout"><code>server.keepAliveTimeout</code></a></li> </ul> </li> <li><a href="#http_class_http_serverresponse">Class: <code>http.ServerResponse</code></a> <ul> <li><a href="#http_event_close_1">Event: <code>'close'</code></a></li> <li><a href="#http_event_finish">Event: <code>'finish'</code></a></li> <li><a href="#http_response_addtrailers_headers"><code>response.addTrailers(headers)</code></a></li> <li><span class="stability_0"><a href="#http_response_connection"><code>response.connection</code></a></span></li> <li><a href="#http_response_cork"><code>response.cork()</code></a></li> <li><a href="#http_response_end_data_encoding_callback"><code>response.end([data[, encoding]][, callback])</code></a></li> <li><span class="stability_0"><a href="#http_response_finished"><code>response.finished</code></a></span></li> <li><a href="#http_response_flushheaders"><code>response.flushHeaders()</code></a></li> <li><a href="#http_response_getheader_name"><code>response.getHeader(name)</code></a></li> <li><a href="#http_response_getheadernames"><code>response.getHeaderNames()</code></a></li> <li><a href="#http_response_getheaders"><code>response.getHeaders()</code></a></li> <li><a href="#http_response_hasheader_name"><code>response.hasHeader(name)</code></a></li> <li><a href="#http_response_headerssent"><code>response.headersSent</code></a></li> <li><a href="#http_response_removeheader_name"><code>response.removeHeader(name)</code></a></li> <li><a href="#http_response_senddate"><code>response.sendDate</code></a></li> <li><a href="#http_response_setheader_name_value"><code>response.setHeader(name, value)</code></a></li> <li><a href="#http_response_settimeout_msecs_callback"><code>response.setTimeout(msecs[, callback])</code></a></li> <li><a href="#http_response_socket"><code>response.socket</code></a></li> <li><a href="#http_response_statuscode"><code>response.statusCode</code></a></li> <li><a href="#http_response_statusmessage"><code>response.statusMessage</code></a></li> <li><a href="#http_response_uncork"><code>response.uncork()</code></a></li> <li><a href="#http_response_writableended"><code>response.writableEnded</code></a></li> <li><a href="#http_response_writablefinished"><code>response.writableFinished</code></a></li> <li><a href="#http_response_write_chunk_encoding_callback"><code>response.write(chunk[, encoding][, callback])</code></a></li> <li><a href="#http_response_writecontinue"><code>response.writeContinue()</code></a></li> <li><a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li> <li><a href="#http_response_writeprocessing"><code>response.writeProcessing()</code></a></li> </ul> </li> <li><a href="#http_class_http_incomingmessage">Class: <code>http.IncomingMessage</code></a> <ul> <li><a href="#http_event_aborted">Event: <code>'aborted'</code></a></li> <li><a href="#http_event_close_2">Event: <code>'close'</code></a></li> <li><a href="#http_message_aborted"><code>message.aborted</code></a></li> <li><a href="#http_message_complete"><code>message.complete</code></a></li> <li><a href="#http_message_destroy_error"><code>message.destroy([error])</code></a></li> <li><a href="#http_message_headers"><code>message.headers</code></a></li> <li><a href="#http_message_httpversion"><code>message.httpVersion</code></a></li> <li><a href="#http_message_method"><code>message.method</code></a></li> <li><a href="#http_message_rawheaders"><code>message.rawHeaders</code></a></li> <li><a href="#http_message_rawtrailers"><code>message.rawTrailers</code></a></li> <li><a href="#http_message_settimeout_msecs_callback"><code>message.setTimeout(msecs[, callback])</code></a></li> <li><a href="#http_message_socket"><code>message.socket</code></a></li> <li><a href="#http_message_statuscode"><code>message.statusCode</code></a></li> <li><a href="#http_message_statusmessage"><code>message.statusMessage</code></a></li> <li><a href="#http_message_trailers"><code>message.trailers</code></a></li> <li><a href="#http_message_url"><code>message.url</code></a></li> </ul> </li> <li><a href="#http_class_http_outgoingmessage">Class: <code>http.OutgoingMessage</code></a> <ul> <li><a href="#http_event_drain">Event: <code>drain</code></a></li> <li><a href="#http_event_finish_1">Event: <code>finish</code></a></li> <li><a href="#http_event_prefinish">Event: <code>prefinish</code></a></li> <li><a href="#http_outgoingmessage_addtrailers_headers"><code>outgoingMessage.addTrailers(headers)</code></a></li> <li><span class="stability_0"><a href="#http_outgoingmessage_connection"><code>outgoingMessage.connection</code></a></span></li> <li><a href="#http_outgoingmessage_cork"><code>outgoingMessage.cork()</code></a></li> <li><a href="#http_outgoingmessage_destroy_error"><code>outgoingMessage.destroy([error])</code></a></li> <li><a href="#http_outgoingmessage_end_chunk_encoding_callback"><code>outgoingMessage.end(chunk[, encoding][, callback])</code></a></li> <li><a href="#http_outgoingmessage_flushheaders"><code>outgoingMessage.flushHeaders()</code></a></li> <li><a href="#http_outgoingmessage_getheader_name"><code>outgoingMessage.getHeader(name)</code></a></li> <li><a href="#http_outgoingmessage_getheadernames"><code>outgoingMessage.getHeaderNames()</code></a></li> <li><a href="#http_outgoingmessage_getheaders"><code>outgoingMessage.getHeaders()</code></a></li> <li><a href="#http_outgoingmessage_hasheader_name"><code>outgoingMessage.hasHeader(name)</code></a></li> <li><a href="#http_outgoingmessage_headerssent"><code>outgoingMessage.headersSent</code></a></li> <li><a href="#http_outgoingmessage_pipe"><code>outgoingMessage.pipe()</code></a></li> <li><a href="#http_outgoingmessage_removeheader"><code>outgoingMessage.removeHeader()</code></a></li> <li><a href="#http_outgoingmessage_setheader_name_value"><code>outgoingMessage.setHeader(name, value)</code></a></li> <li><a href="#http_outgoingmessage_settimeout_msesc_callback"><code>outgoingMessage.setTimeout(msesc[, callback])</code></a></li> <li><a href="#http_outgoingmessage_socket"><code>outgoingMessage.socket</code></a></li> <li><a href="#http_outgoingmessage_uncork"><code>outgoingMessage.uncork()</code></a></li> <li><a href="#http_outgoingmessage_writablecorked"><code>outgoingMessage.writableCorked</code></a></li> <li><a href="#http_outgoingmessage_writableended"><code>outgoingMessage.writableEnded</code></a></li> <li><a href="#http_outgoingmessage_writablefinished"><code>outgoingMessage.writableFinished</code></a></li> <li><a href="#http_outgoingmessage_writablehighwatermark"><code>outgoingMessage.writableHighWaterMark</code></a></li> <li><a href="#http_outgoingmessage_writablelength"><code>outgoingMessage.writableLength</code></a></li> <li><a href="#http_outgoingmessage_writableobjectmode"><code>outgoingMessage.writableObjectMode</code></a></li> <li><a href="#http_outgoingmessage_write_chunk_encoding_callback"><code>outgoingMessage.write(chunk[, encoding][, callback])</code></a></li> </ul> </li> <li><a href="#http_http_methods"><code>http.METHODS</code></a></li> <li><a href="#http_http_status_codes"><code>http.STATUS_CODES</code></a></li> <li><a href="#http_http_createserver_options_requestlistener"><code>http.createServer([options][, requestListener])</code></a></li> <li><a href="#http_http_get_options_callback"><code>http.get(options[, callback])</code></a></li> <li><a href="#http_http_get_url_options_callback"><code>http.get(url[, options][, callback])</code></a></li> <li><a href="#http_http_globalagent"><code>http.globalAgent</code></a></li> <li><a href="#http_http_maxheadersize"><code>http.maxHeaderSize</code></a></li> <li><a href="#http_http_request_options_callback"><code>http.request(options[, callback])</code></a></li> <li><a href="#http_http_request_url_options_callback"><code>http.request(url[, options][, callback])</code></a></li> <li><a href="#http_http_validateheadername_name"><code>http.validateHeaderName(name)</code></a></li> <li><a href="#http_http_validateheadervalue_name_value"><code>http.validateHeaderValue(name, value)</code></a></li> </ul> </li> </ul></details> <div id="apicontent"> <h2>HTTP<span><a class="mark" href="#http_http" id="http_http">#</a></span></h2> <p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.21.3/lib/http.js">lib/http.js</a></p> <p>To use the HTTP server and client one must <code>require('http')</code>.</p> <p>The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.</p> <p>HTTP message headers are represented by an object like this:</p> <!-- eslint-skip --> <pre><code class="language-js">{ <span class="hljs-string">'content-length'</span>: <span class="hljs-string">'123'</span>, <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain'</span>, <span class="hljs-string">'connection'</span>: <span class="hljs-string">'keep-alive'</span>, <span class="hljs-string">'host'</span>: <span class="hljs-string">'mysite.com'</span>, <span class="hljs-string">'accept'</span>: <span class="hljs-string">'*/*'</span> }</code></pre> <p>Keys are lowercased. Values are not modified.</p> <p>In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.</p> <p>See <a href="#http_message_headers"><code>message.headers</code></a> for details on how duplicate headers are handled.</p> <p>The raw headers as they were received are retained in the <code>rawHeaders</code> property, which is an array of <code>[key, value, key2, value2, ...]</code>. For example, the previous message header object might have a <code>rawHeaders</code> list like the following:</p> <!-- eslint-disable semi --> <pre><code class="language-js">[ <span class="hljs-string">'ConTent-Length'</span>, <span class="hljs-string">'123456'</span>, <span class="hljs-string">'content-LENGTH'</span>, <span class="hljs-string">'123'</span>, <span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/plain'</span>, <span class="hljs-string">'CONNECTION'</span>, <span class="hljs-string">'keep-alive'</span>, <span class="hljs-string">'Host'</span>, <span class="hljs-string">'mysite.com'</span>, <span class="hljs-string">'accepT'</span>, <span class="hljs-string">'*/*'</span> ]</code></pre> <section><h3>Class: <code>http.Agent</code><span><a class="mark" href="#http_class_http_agent" id="http_class_http_agent">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>An <code>Agent</code> is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the <code>keepAlive</code> <a href="#http_new_agent_options">option</a>.</p> <p>Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed from the pool and a new connection will be made when a new HTTP request is made for that host and port. Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every request and cannot be pooled. The <code>Agent</code> will still make the requests to that server, but each one will occur over a new connection.</p> <p>When a connection is closed by the client or the server, it is removed from the pool. Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests. (see <a href="net.html#net_socket_unref"><code>socket.unref()</code></a>).</p> <p>It is good practice, to <a href="#http_agent_destroy"><code>destroy()</code></a> an <code>Agent</code> instance when it is no longer in use, because unused sockets consume OS resources.</p> <p>Sockets are removed from an agent when the socket emits either a <code>'close'</code> event or an <code>'agentRemove'</code> event. When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done:</p> <pre><code class="language-js">http.<span class="hljs-title function_">get</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-comment">// Do stuff</span> }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'socket'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { socket.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'agentRemove'</span>); });</code></pre> <p>An agent may also be used for an individual request. By providing <code>{agent: false}</code> as an option to the <code>http.get()</code> or <code>http.request()</code> functions, a one-time use <code>Agent</code> with default options will be used for the client connection.</p> <p><code>agent:false</code>:</p> <pre><code class="language-js">http.<span class="hljs-title function_">get</span>({ <span class="hljs-attr">hostname</span>: <span class="hljs-string">'localhost'</span>, <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>, <span class="hljs-attr">agent</span>: <span class="hljs-literal">false</span> <span class="hljs-comment">// Create a new agent just for this one request</span> }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-comment">// Do stuff with response</span> });</code></pre> <h4><code>new Agent([options])</code><span><a class="mark" href="#http_new_agent_options" id="http_new_agent_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.17.0</td> <td><p>Change the default scheduling from 'fifo' to 'lifo'.</p></td></tr> <tr><td>v14.5.0</td> <td><p>Add <code>maxTotalSockets</code> option to agent constructor.</p></td></tr> <tr><td>v14.5.0</td> <td><p>Add <code>scheduling</code> option to specify the free socket scheduling strategy.</p></td></tr> <tr><td>v0.3.4</td> <td><p><span>Added in: v0.3.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Set of configurable options to set on the agent. Can have the following fields: <ul> <li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the <code>keep-alive</code> value of the <code>Connection</code> header. The <code>Connection: keep-alive</code> header is always sent when using an agent except when the <code>Connection</code> header is explicitly specified or when the <code>keepAlive</code> and <code>maxSockets</code> options are respectively set to <code>false</code> and <code>Infinity</code>, in which case <code>Connection: close</code> will be used. <strong>Default:</strong> <code>false</code>.</li> <li><code>keepAliveMsecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> When using the <code>keepAlive</code> option, specifies the <a href="net.html#net_socket_setkeepalive_enable_initialdelay">initial delay</a> for TCP Keep-Alive packets. Ignored when the <code>keepAlive</code> option is <code>false</code> or <code>undefined</code>. <strong>Default:</strong> <code>1000</code>.</li> <li><code>maxSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until the <code>maxSockets</code> value is reached. If the host attempts to open more connections than <code>maxSockets</code>, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at most <code>maxSockets</code> active connections at any point in time, from a given host. <strong>Default:</strong> <code>Infinity</code>.</li> <li><code>maxTotalSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. <strong>Default:</strong> <code>Infinity</code>.</li> <li><code>maxFreeSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets to leave open in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>. <strong>Default:</strong> <code>256</code>.</li> <li><code>scheduling</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Scheduling strategy to apply when picking the next free socket to use. It can be <code>'fifo'</code> or <code>'lifo'</code>. The main difference between the two scheduling strategies is that <code>'lifo'</code> selects the most recently used socket, while <code>'fifo'</code> selects the least recently used socket. In case of a low rate of request per second, the <code>'lifo'</code> scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the <code>'fifo'</code> scheduling will maximize the number of open sockets, while the <code>'lifo'</code> scheduling will keep it as low as possible. <strong>Default:</strong> <code>'lifo'</code>.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Socket timeout in milliseconds. This will set the timeout when the socket is created.</li> </ul> </li> </ul> <p><code>options</code> in <a href="net.html#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> are also supported.</p> <p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="#http_http_request_options_callback"><code>http.request()</code></a> has all of these values set to their respective defaults.</p> <p>To configure any of them, a custom <a href="#http_class_http_agent"><code>http.Agent</code></a> instance must be created.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> keepAliveAgent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> }); options.<span class="hljs-property">agent</span> = keepAliveAgent; http.<span class="hljs-title function_">request</span>(options, onResponseCallback);</code></pre> <h4><code>agent.createConnection(options[, callback])</code><span><a class="mark" href="#http_agent_createconnection_options_callback" id="http_agent_createconnection_options_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options containing connection details. Check <a href="net.html#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a> for the format of the options</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function that receives the created socket</li> <li>Returns: <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Produces a socket/stream to be used for HTTP requests.</p> <p>By default, this function is the same as <a href="net.html#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a>. However, custom agents may override this method in case greater flexibility is desired.</p> <p>A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function, or by passing the socket/stream to <code>callback</code>.</p> <p>This method is guaranteed to return an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <p><code>callback</code> has a signature of <code>(err, stream)</code>.</p> <h4><code>agent.keepSocketAlive(socket)</code><span><a class="mark" href="#http_agent_keepsocketalive_socket" id="http_agent_keepsocketalive_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Called when <code>socket</code> is detached from a request and could be persisted by the <code>Agent</code>. Default behavior is to:</p> <pre><code class="language-js">socket.<span class="hljs-title function_">setKeepAlive</span>(<span class="hljs-literal">true</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">keepAliveMsecs</span>); socket.<span class="hljs-title function_">unref</span>(); <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;</code></pre> <p>This method can be overridden by a particular <code>Agent</code> subclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.</p> <p>The <code>socket</code> argument can be an instance of <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>.</p> <h4><code>agent.reuseSocket(socket, request)</code><span><a class="mark" href="#http_agent_reusesocket_socket_request" id="http_agent_reusesocket_socket_request">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> <li><code>request</code> <a href="http.html#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Called when <code>socket</code> is attached to <code>request</code> after being persisted because of the keep-alive options. Default behavior is to:</p> <pre><code class="language-js">socket.<span class="hljs-title function_">ref</span>();</code></pre> <p>This method can be overridden by a particular <code>Agent</code> subclass.</p> <p>The <code>socket</code> argument can be an instance of <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>.</p> <h4><code>agent.destroy()</code><span><a class="mark" href="#http_agent_destroy" id="http_agent_destroy">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>Destroy any sockets that are currently in use by the agent.</p> <p>It is usually not necessary to do this. However, if using an agent with <code>keepAlive</code> enabled, then it is best to explicitly shut down the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them.</p> <h4><code>agent.freeSockets</code><span><a class="mark" href="#http_agent_freesockets" id="http_agent_freesockets">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains arrays of sockets currently awaiting use by the agent when <code>keepAlive</code> is enabled. Do not modify.</p> <p>Sockets in the <code>freeSockets</code> list will be automatically destroyed and removed from the array on <code>'timeout'</code>.</p> <h4><code>agent.getName(options)</code><span><a class="mark" href="#http_agent_getname_options" id="http_agent_getname_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A set of options providing information for name generation <ul> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the request to</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server</li> <li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections when issuing the request</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Must be 4 or 6 if this doesn't equal <code>undefined</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returns <code>host:port:localAddress</code> or <code>host:port:localAddress:family</code>. For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.</p> <h4><code>agent.maxFreeSockets</code><span><a class="mark" href="#http_agent_maxfreesockets" id="http_agent_maxfreesockets">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>By default set to 256. For agents with <code>keepAlive</code> enabled, this sets the maximum number of sockets that will be left open in the free state.</p> <h4><code>agent.maxSockets</code><span><a class="mark" href="#http_agent_maxsockets" id="http_agent_maxsockets">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of <a href="#http_agent_getname_options"><code>agent.getName()</code></a>.</p> <h4><code>agent.maxTotalSockets</code><span><a class="mark" href="#http_agent_maxtotalsockets" id="http_agent_maxtotalsockets">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent can have open. Unlike <code>maxSockets</code>, this parameter applies across all origins.</p> <h4><code>agent.requests</code><span><a class="mark" href="#http_agent_requests" id="http_agent_requests">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.</p> <h4><code>agent.sockets</code><span><a class="mark" href="#http_agent_sockets" id="http_agent_sockets">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains arrays of sockets currently in use by the agent. Do not modify.</p> </section><section><h3>Class: <code>http.ClientRequest</code><span><a class="mark" href="#http_class_http_clientrequest" id="http_class_http_clientrequest">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li>Extends: <a href="stream.html#stream_stream" class="type"><Stream></a></li> </ul> <p>This object is created internally and returned from <a href="#http_http_request_options_callback"><code>http.request()</code></a>. It represents an <em>in-progress</em> request whose header has already been queued. The header is still mutable using the <a href="#http_request_setheader_name_value"><code>setHeader(name, value)</code></a>, <a href="#http_request_getheader_name"><code>getHeader(name)</code></a>, <a href="#http_request_removeheader_name"><code>removeHeader(name)</code></a> API. The actual header will be sent along with the first data chunk or when calling <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a>.</p> <p>To get the response, add a listener for <a href="#http_event_response"><code>'response'</code></a> to the request object. <a href="#http_event_response"><code>'response'</code></a> will be emitted from the request object when the response headers have been received. The <a href="#http_event_response"><code>'response'</code></a> event is executed with one argument which is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p> <p>During the <a href="#http_event_response"><code>'response'</code></a> event, one can add listeners to the response object; particularly to listen for the <code>'data'</code> event.</p> <p>If no <a href="#http_event_response"><code>'response'</code></a> handler is added, then the response will be entirely discarded. However, if a <a href="#http_event_response"><code>'response'</code></a> event handler is added, then the data from the response object <strong>must</strong> be consumed, either by calling <code>response.read()</code> whenever there is a <code>'readable'</code> event, or by adding a <code>'data'</code> handler, or by calling the <code>.resume()</code> method. Until the data is consumed, the <code>'end'</code> event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.</p> <p>Unlike the <code>request</code> object, if the response closes prematurely, the <code>response</code> object does not emit an <code>'error'</code> event but instead emits the <code>'aborted'</code> event.</p> <p>Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.</p> <h4>Event: <code>'abort'</code><span><a class="mark" href="#http_event_abort" id="http_event_abort">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.4.1</span> </div> <p>Emitted when the request has been aborted by the client. This event is only emitted on the first call to <code>abort()</code>.</p> <h4>Event: <code>'connect'</code><span><a class="mark" href="#http_event_connect" id="http_event_connect">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>response</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> <li><code>head</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Emitted each time a server responds to a request with a <code>CONNECT</code> method. If this event is not being listened for, clients receiving a <code>CONNECT</code> method will have their connections closed.</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <p>A client and server pair demonstrating how to listen for the <code>'connect'</code> event:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'net'</span>); <span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">URL</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'url'</span>); <span class="hljs-comment">// Create an HTTP tunneling proxy</span> <span class="hljs-keyword">const</span> proxy = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>); }); proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">req, clientSocket, head</span>) =></span> { <span class="hljs-comment">// Connect to an origin server</span> <span class="hljs-keyword">const</span> { port, hostname } = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${req.url}</span>`</span>); <span class="hljs-keyword">const</span> serverSocket = net.<span class="hljs-title function_">connect</span>(port || <span class="hljs-number">80</span>, hostname, <span class="hljs-function">() =></span> { clientSocket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 200 Connection Established\r\n'</span> + <span class="hljs-string">'Proxy-agent: Node.js-Proxy\r\n'</span> + <span class="hljs-string">'\r\n'</span>); serverSocket.<span class="hljs-title function_">write</span>(head); serverSocket.<span class="hljs-title function_">pipe</span>(clientSocket); clientSocket.<span class="hljs-title function_">pipe</span>(serverSocket); }); }); <span class="hljs-comment">// Now that proxy is running</span> proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">// Make a request to a tunneling proxy</span> <span class="hljs-keyword">const</span> options = { <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>, <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">method</span>: <span class="hljs-string">'CONNECT'</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'www.google.com:80'</span> }; <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options); req.<span class="hljs-title function_">end</span>(); req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, head</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got connected!'</span>); <span class="hljs-comment">// Make a request over an HTTP tunnel</span> socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'GET / HTTP/1.1\r\n'</span> + <span class="hljs-string">'Host: www.google.com:80\r\n'</span> + <span class="hljs-string">'Connection: close\r\n'</span> + <span class="hljs-string">'\r\n'</span>); socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>()); }); socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { proxy.<span class="hljs-title function_">close</span>(); }); }); });</code></pre> <h4>Event: <code>'continue'</code><span><a class="mark" href="#http_event_continue" id="http_event_continue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <p>Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.</p> <h4>Event: <code>'information'</code><span><a class="mark" href="#http_event_information" id="http_event_information">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>httpVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>httpVersionMajor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>httpVersionMinor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> </li> </ul> <p>Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the HTTP version, status code, status message, key-value headers object, and array with the raw header names followed by their respective values.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> options = { <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'/length_request'</span> }; <span class="hljs-comment">// Make a request</span> <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options); req.<span class="hljs-title function_">end</span>(); req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'information'</span>, <span class="hljs-function">(<span class="hljs-params">info</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Got information prior to main response: <span class="hljs-subst">${info.statusCode}</span>`</span>); });</code></pre> <p>101 Upgrade statuses do not fire this event due to their break from the traditional HTTP request/response chain, such as web sockets, in-place TLS upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the <a href="#http_event_upgrade"><code>'upgrade'</code></a> event instead.</p> <h4>Event: <code>'response'</code><span><a class="mark" href="#http_event_response" id="http_event_response">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>response</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> </ul> <p>Emitted when a response is received to this request. This event is emitted only once.</p> <h4>Event: <code>'socket'</code><span><a class="mark" href="#http_event_socket" id="http_event_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.3</span> </div> <ul> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4>Event: <code>'timeout'</code><span><a class="mark" href="#http_event_timeout" id="http_event_timeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.8</span> </div> <p>Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be aborted manually.</p> <p>See also: <a href="#http_request_settimeout_timeout_callback"><code>request.setTimeout()</code></a>.</p> <h4>Event: <code>'upgrade'</code><span><a class="mark" href="#http_event_upgrade" id="http_event_upgrade">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>response</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> <li><code>head</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Emitted each time a server responds to a request with an upgrade. If this event is not being listened for and the response status code is 101 Switching Protocols, clients receiving an upgrade header will have their connections closed.</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <p>A client server pair demonstrating how to listen for the <code>'upgrade'</code> event.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-comment">// Create an HTTP server</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>); }); server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">req, socket, head</span>) =></span> { socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'</span> + <span class="hljs-string">'Upgrade: WebSocket\r\n'</span> + <span class="hljs-string">'Connection: Upgrade\r\n'</span> + <span class="hljs-string">'\r\n'</span>); socket.<span class="hljs-title function_">pipe</span>(socket); <span class="hljs-comment">// echo back</span> }); <span class="hljs-comment">// Now that server is running</span> server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">// make a request</span> <span class="hljs-keyword">const</span> options = { <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>, <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Connection'</span>: <span class="hljs-string">'Upgrade'</span>, <span class="hljs-string">'Upgrade'</span>: <span class="hljs-string">'websocket'</span> } }; <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options); req.<span class="hljs-title function_">end</span>(); req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, upgradeHead</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got upgraded!'</span>); socket.<span class="hljs-title function_">end</span>(); process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>); }); });</code></pre> <h4><code>request.abort()</code><span><a class="mark" href="#http_request_abort" id="http_request_abort">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.8</span><span>Deprecated since: v14.1.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#http_request_destroy_error"><code>request.destroy()</code></a> instead.</div><p></p> <p>Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.</p> <h4><code>request.aborted</code><span><a class="mark" href="#http_request_aborted" id="http_request_aborted">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v11.0.0</td> <td><p>The <code>aborted</code> property is no longer a timestamp number.</p></td></tr> <tr><td>v0.11.14</td> <td><p><span>Added in: v0.11.14</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>request.aborted</code> property will be <code>true</code> if the request has been aborted.</p> <h4><code>request.connection</code><span><a class="mark" href="#http_request_connection" id="http_request_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_request_socket"><code>request.socket</code></a>.</div><p></p> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>See <a href="#http_request_socket"><code>request.socket</code></a>.</p> <h4><code>request.end([data[, encoding]][, callback])</code><span><a class="mark" href="#http_request_end_data_encoding_callback" id="http_request_end_data_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ClientRequest</code>.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating <code>'0\r\n\r\n'</code>.</p> <p>If <code>data</code> is specified, it is equivalent to calling <a href="#http_request_write_chunk_encoding_callback"><code>request.write(data, encoding)</code></a> followed by <code>request.end(callback)</code>.</p> <p>If <code>callback</code> is specified, it will be called when the request stream is finished.</p> <h4><code>request.destroy([error])</code><span><a class="mark" href="#http_request_destroy_error" id="http_request_destroy_error">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.5.0</td> <td><p>The function returns <code>this</code> for consistency with other Readable streams.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Optional, an error to emit with <code>'error'</code> event.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Destroy the request. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> event. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.</p> <p>See <a href="stream.html#stream_writable_destroy_error"><code>writable.destroy()</code></a> for further details.</p> <h5><code>request.destroyed</code><span><a class="mark" href="#http_request_destroyed" id="http_request_destroyed">#</a></span></h5> <div class="api_metadata"> <span>Added in: v14.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> after <a href="#http_request_destroy_error"><code>request.destroy()</code></a> has been called.</p> <p>See <a href="stream.html#stream_writable_destroyed"><code>writable.destroyed</code></a> for further details.</p> <h4><code>request.finished</code><span><a class="mark" href="#http_request_finished" id="http_request_finished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.0.1</span><span>Deprecated since: v13.4.0, v12.16.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_request_writableended"><code>request.writableEnded</code></a>.</div><p></p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>request.finished</code> property will be <code>true</code> if <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a> has been called. <code>request.end()</code> will automatically be called if the request was initiated via <a href="#http_http_get_options_callback"><code>http.get()</code></a>.</p> <h4><code>request.flushHeaders()</code><span><a class="mark" href="#http_request_flushheaders" id="http_request_flushheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <p>Flushes the request headers.</p> <p>For efficiency reasons, Node.js normally buffers the request headers until <code>request.end()</code> is called or the first chunk of request data is written. It then tries to pack the request headers and data into a single TCP packet.</p> <p>That's usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. <code>request.flushHeaders()</code> bypasses the optimization and kickstarts the request.</p> <h4><code>request.getHeader(name)</code><span><a class="mark" href="#http_request_getheader_name" id="http_request_getheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Reads out a header on the request. The name is case-insensitive. The type of the return value depends on the arguments provided to <a href="#http_request_setheader_name_value"><code>request.setHeader()</code></a>.</p> <pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/html'</span>); request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body)); request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]); <span class="hljs-keyword">const</span> contentType = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Type'</span>); <span class="hljs-comment">// 'contentType' is 'text/html'</span> <span class="hljs-keyword">const</span> contentLength = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>); <span class="hljs-comment">// 'contentLength' is of type number</span> <span class="hljs-keyword">const</span> cookie = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Cookie'</span>); <span class="hljs-comment">// 'cookie' is of type string[]</span></code></pre> <h4><code>request.getRawHeaderNames()</code><span><a class="mark" href="#http_request_getrawheadernames" id="http_request_getrawheadernames">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.17.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.</p> <pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>); request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]); <span class="hljs-keyword">const</span> headerNames = request.<span class="hljs-title function_">getRawHeaderNames</span>(); <span class="hljs-comment">// headerNames === ['Foo', 'Set-Cookie']</span></code></pre> <h4><code>request.maxHeadersCount</code><span><a class="mark" href="#http_request_maxheaderscount" id="http_request_maxheaderscount">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li> </ul> <p>Limits maximum response headers count. If set to 0, no limit will be applied.</p> <h4><code>request.path</code><span><a class="mark" href="#http_request_path" id="http_request_path">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request path.</li> </ul> <h4><code>request.method</code><span><a class="mark" href="#http_request_method" id="http_request_method">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.97</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request method.</li> </ul> <h4><code>request.host</code><span><a class="mark" href="#http_request_host" id="http_request_host">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request host.</li> </ul> <h4><code>request.protocol</code><span><a class="mark" href="#http_request_protocol" id="http_request_protocol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request protocol.</li> </ul> <h4><code>request.removeHeader(name)</code><span><a class="mark" href="#http_request_removeheader_name" id="http_request_removeheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that's already defined into headers object.</p> <pre><code class="language-js">request.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Type'</span>);</code></pre> <h4><code>request.reusedSocket</code><span><a class="mark" href="#http_request_reusedsocket" id="http_request_reusedsocket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0, v12.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the request is send through a reused socket.</li> </ul> <p>When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-comment">// Server has a 5 seconds keep-alive timeout by default</span> http .<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\n'</span>); res.<span class="hljs-title function_">end</span>(); }) .<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>); <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> { <span class="hljs-comment">// Adapting a keep-alive agent</span> http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> { <span class="hljs-comment">// Do nothing</span> }); }); }, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Sending request on 5s interval so it's easy to hit idle timeout</span></code></pre> <p>By marking a request whether it reused socket or not, we can do automatic error retry base on it.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> agent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> }); <span class="hljs-keyword">function</span> <span class="hljs-title function_">retriableRequest</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> req = http .<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-comment">// ...</span> }) .<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { <span class="hljs-comment">// Check if retry is needed</span> <span class="hljs-keyword">if</span> (req.<span class="hljs-property">reusedSocket</span> && err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span>) { <span class="hljs-title function_">retriableRequest</span>(); } }); } <span class="hljs-title function_">retriableRequest</span>();</code></pre> <h4><code>request.setHeader(name, value)</code><span><a class="mark" href="#http_request_setheader_name_value" id="http_request_setheader_name_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Sets a single header value for headers object. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, <a href="#http_request_getheader_name"><code>request.getHeader()</code></a> may return non-string values. However, the non-string values will be converted to strings for network transmission.</p> <pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>);</code></pre> <p>or</p> <pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code></pre> <h4><code>request.setNoDelay([noDelay])</code><span><a class="mark" href="#http_request_setnodelay_nodelay" id="http_request_setnodelay_nodelay">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="net.html#net_socket_setnodelay_nodelay"><code>socket.setNoDelay()</code></a> will be called.</p> <h4><code>request.setSocketKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#http_request_setsocketkeepalive_enable_initialdelay" id="http_request_setsocketkeepalive_enable_initialdelay">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> <li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="net.html#net_socket_setkeepalive_enable_initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p> <h4><code>request.setTimeout(timeout[, callback])</code><span><a class="mark" href="#http_request_settimeout_timeout_callback" id="http_request_settimeout_timeout_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Consistently set socket timeout only when the socket connects.</p></td></tr> <tr><td>v0.5.9</td> <td><p><span>Added in: v0.5.9</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Milliseconds before a request times out.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional function to be called when a timeout occurs. Same as binding to the <code>'timeout'</code> event.</li> <li>Returns: <a href="http.html#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="net.html#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called.</p> <h4><code>request.socket</code><span><a class="mark" href="#http_request_socket" id="http_request_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> options = { <span class="hljs-attr">host</span>: <span class="hljs-string">'www.google.com'</span>, }; <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">get</span>(options); req.<span class="hljs-title function_">end</span>(); req.<span class="hljs-title function_">once</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localAddress</span>; <span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localPort</span>; <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>); <span class="hljs-comment">// Consume response object</span> });</code></pre> <p>This property is guaranteed to be an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specified a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4><code>request.writableEnded</code><span><a class="mark" href="#http_request_writableended" id="http_request_writableended">#</a></span></h4> <div class="api_metadata"> <span>Added in: v12.9.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> after <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a> has been called. This property does not indicate whether the data has been flushed, for this use <a href="#http_request_writablefinished"><code>request.writableFinished</code></a> instead.</p> <h4><code>request.writableFinished</code><span><a class="mark" href="#http_request_writablefinished" id="http_request_writablefinished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v12.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if all data has been flushed to the underlying system, immediately before the <a href="#http_event_finish"><code>'finish'</code></a> event is emitted.</p> <h4><code>request.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#http_request_write_chunk_encoding_callback" id="http_request_write_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.29</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sends a chunk of the body. This method can be called multiple times. If no <code>Content-Length</code> is set, data will automatically be encoded in HTTP Chunked transfer encoding, so that server knows when the data ends. The <code>Transfer-Encoding: chunked</code> header is added. Calling <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a> is necessary to finish sending the request.</p> <p>The <code>encoding</code> argument is optional and only applies when <code>chunk</code> is a string. Defaults to <code>'utf8'</code>.</p> <p>The <code>callback</code> argument is optional and will be called when this chunk of data is flushed, but only if the chunk is non-empty.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <p>When <code>write</code> function is called with empty string or buffer, it does nothing and waits for more input.</p> </section><section><h3>Class: <code>http.Server</code><span><a class="mark" href="#http_class_http_server" id="http_class_http_server">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li>Extends: <a href="net.html#net_class_net_server" class="type"><net.Server></a></li> </ul> <h4>Event: <code>'checkContinue'</code><span><a class="mark" href="#http_event_checkcontinue" id="http_event_checkcontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>When this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: <code>'checkExpectation'</code><span><a class="mark" href="#http_event_checkexpectation" id="http_event_checkexpectation">#</a></span></h4> <div class="api_metadata"> <span>Added in: v5.5.0</span> </div> <ul> <li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time a request with an HTTP <code>Expect</code> header is received, where the value is not <code>100-continue</code>. If this event is not listened for, the server will automatically respond with a <code>417 Expectation Failed</code> as appropriate.</p> <p>When this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: <code>'clientError'</code><span><a class="mark" href="#http_event_clienterror" id="http_event_clienterror">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v12.0.0</td> <td><p>The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.</p></td></tr> <tr><td>v9.4.0</td> <td><p>The <code>rawPacket</code> is the current buffer that just parsed. Adding this buffer to the error object of <code>'clientError'</code> event is to make it possible that developers can log the broken packet.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default action of calling <code>.destroy()</code> on the <code>socket</code> will no longer take place if there are listeners attached for <code>'clientError'</code>.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>If a client connection emits an <code>'error'</code> event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <p>Default behavior is to try close the socket with a HTTP '400 Bad Request', or a HTTP '431 Request Header Fields Too Large' in the case of a <a href="errors.html#errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a> error. If the socket is not writable or has already written data it is immediately destroyed.</p> <p><code>socket</code> is the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">end</span>(); }); server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> { socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>); }); server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code></pre> <p>When the <code>'clientError'</code> event occurs, there is no <code>request</code> or <code>response</code> object, so any HTTP response sent, including response headers and payload, <em>must</em> be written directly to the <code>socket</code> object. Care must be taken to ensure the response is a properly formatted HTTP response message.</p> <p><code>err</code> is an instance of <code>Error</code> with two extra columns:</p> <ul> <li><code>bytesParsed</code>: the bytes count of request packet that Node.js may have parsed correctly;</li> <li><code>rawPacket</code>: the raw packet of current request.</li> </ul> <p>In some cases, the client has already received the response and/or the socket has already been destroyed, like in case of <code>ECONNRESET</code> errors. Before trying to send data to the socket, it is better to check that it is still writable.</p> <pre><code class="language-js">server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> { <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span> || !socket.<span class="hljs-property">writable</span>) { <span class="hljs-keyword">return</span>; } socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>); });</code></pre> <h4>Event: <code>'close'</code><span><a class="mark" href="#http_event_close" id="http_event_close">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.4</span> </div> <p>Emitted when the server closes.</p> <h4>Event: <code>'connect'</code><span><a class="mark" href="#http_event_connect_1" id="http_event_connect_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in the <a href="#http_event_request"><code>'request'</code></a> event</li> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a> Network socket between the server and client</li> <li><code>head</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The first packet of the tunneling stream (may be empty)</li> </ul> <p>Emitted each time a client requests an HTTP <code>CONNECT</code> method. If this event is not listened for, then clients requesting a <code>CONNECT</code> method will have their connections closed.</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <p>After this event is emitted, the request's socket will not have a <code>'data'</code> event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.</p> <h4>Event: <code>'connection'</code><span><a class="mark" href="#http_event_connection" id="http_event_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>This event is emitted when a new TCP stream is established. <code>socket</code> is typically an object of type <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>. Usually users will not want to access this event. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. The <code>socket</code> can also be accessed at <code>request.socket</code>.</p> <p>This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any <a href="stream.html#stream_class_stream_duplex"><code>Duplex</code></a> stream can be passed.</p> <p>If <code>socket.setTimeout()</code> is called here, the timeout will be replaced with <code>server.keepAliveTimeout</code> when the socket has served a request (if <code>server.keepAliveTimeout</code> is non-zero).</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4>Event: <code>'request'</code><span><a class="mark" href="#http_event_request" id="http_event_request">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).</p> <h4>Event: <code>'upgrade'</code><span><a class="mark" href="#http_event_upgrade_1" id="http_event_upgrade_1">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in the <a href="#http_event_request"><code>'request'</code></a> event</li> <li><code>socket</code> <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a> Network socket between the server and client</li> <li><code>head</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The first packet of the upgraded stream (may be empty)</li> </ul> <p>Emitted each time a client requests an HTTP upgrade. Listening to this event is optional and clients cannot insist on a protocol change.</p> <p>After this event is emitted, the request's socket will not have a <code>'data'</code> event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.</p> <p>This event is guaranteed to be passed an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specifies a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4><code>server.close([callback])</code><span><a class="mark" href="#http_server_close_callback" id="http_server_close_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="net.html#net_server_close_callback"><code>net.Server.close()</code></a>.</p> <h4><code>server.headersTimeout</code><span><a class="mark" href="#http_server_headerstimeout" id="http_server_headerstimeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v11.3.0, v10.14.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>60000</code></li> </ul> <p>Limit the amount of time the parser will wait to receive the complete HTTP headers.</p> <p>In case of inactivity, the rules defined in <a href="#http_server_timeout"><code>server.timeout</code></a> apply. However, that inactivity based timeout would still allow the connection to be kept open if the headers are being sent very slowly (by default, up to a byte per 2 minutes). In order to prevent this, whenever header data arrives an additional check is made that more than <code>server.headersTimeout</code> milliseconds has not passed since the connection was established. If the check fails, a <code>'timeout'</code> event is emitted on the server object, and (by default) the socket is destroyed. See <a href="#http_server_timeout"><code>server.timeout</code></a> for more information on how timeout behavior can be customized.</p> <h4><code>server.listen()</code><span><a class="mark" href="#http_server_listen" id="http_server_listen">#</a></span></h4> <p>Starts the HTTP server listening for connections. This method is identical to <a href="net.html#net_server_listen"><code>server.listen()</code></a> from <a href="net.html#net_class_net_server"><code>net.Server</code></a>.</p> <h4><code>server.listening</code><span><a class="mark" href="#http_server_listening" id="http_server_listening">#</a></span></h4> <div class="api_metadata"> <span>Added in: v5.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether or not the server is listening for connections.</li> </ul> <h4><code>server.maxHeadersCount</code><span><a class="mark" href="#http_server_maxheaderscount" id="http_server_maxheaderscount">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li> </ul> <p>Limits maximum incoming headers count. If set to 0, no limit will be applied.</p> <h4><code>server.requestTimeout</code><span><a class="mark" href="#http_server_requesttimeout" id="http_server_requesttimeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.11.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> </ul> <p>Sets the timeout value in milliseconds for receiving the entire request from the client.</p> <p>If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.</p> <p>It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.</p> <h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#http_server_settimeout_msecs_callback" id="http_server_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v13.0.0</td> <td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr> <tr><td>v0.9.12</td> <td><p><span>Added in: v0.9.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> 0 (no timeout)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http.html#http_class_http_server" class="type"><http.Server></a></li> </ul> <p>Sets the timeout value for sockets, and emits a <code>'timeout'</code> event on the Server object, passing the socket as an argument, if a timeout occurs.</p> <p>If there is a <code>'timeout'</code> event listener on the Server object, then it will be called with the timed-out socket as an argument.</p> <p>By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's <code>'timeout'</code> event, timeouts must be handled explicitly.</p> <h4><code>server.timeout</code><span><a class="mark" href="#http_server_timeout" id="http_server_timeout">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v13.0.0</td> <td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr> <tr><td>v0.9.12</td> <td><p><span>Added in: v0.9.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> 0 (no timeout)</li> </ul> <p>The number of milliseconds of inactivity before a socket is presumed to have timed out.</p> <p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p> <p>The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.</p> <h4><code>server.keepAliveTimeout</code><span><a class="mark" href="#http_server_keepalivetimeout" id="http_server_keepalivetimeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> <code>5000</code> (5 seconds).</li> </ul> <p>The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., <a href="#http_server_timeout"><code>server.timeout</code></a>.</p> <p>A value of <code>0</code> will disable the keep-alive timeout behavior on incoming connections. A value of <code>0</code> makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.</p> <p>The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.</p> </section><section><h3>Class: <code>http.ServerResponse</code><span><a class="mark" href="#http_class_http_serverresponse" id="http_class_http_serverresponse">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li>Extends: <a href="stream.html#stream_stream" class="type"><Stream></a></li> </ul> <p>This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the <a href="#http_event_request"><code>'request'</code></a> event.</p> <h4>Event: <code>'close'</code><span><a class="mark" href="#http_event_close_1" id="http_event_close_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.6.7</span> </div> <p>Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion).</p> <h4>Event: <code>'finish'</code><span><a class="mark" href="#http_event_finish" id="http_event_finish">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <p>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.</p> <h4><code>response.addTrailers(headers)</code><span><a class="mark" href="#http_response_addtrailers_headers" id="http_response_addtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>This method adds HTTP trailing headers (a header but at the end of the message) to the response.</p> <p>Trailers will <strong>only</strong> be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.</p> <p>HTTP requires the <code>Trailer</code> header to be sent in order to emit trailers, with a list of the header fields in its value. E.g.,</p> <pre><code class="language-js">response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>, <span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> }); response.<span class="hljs-title function_">write</span>(fileData); response.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> }); response.<span class="hljs-title function_">end</span>();</code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4><code>response.connection</code><span><a class="mark" href="#http_response_connection" id="http_response_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_response_socket"><code>response.socket</code></a>.</div><p></p> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>See <a href="#http_response_socket"><code>response.socket</code></a>.</p> <h4><code>response.cork()</code><span><a class="mark" href="#http_response_cork" id="http_response_cork">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.2.0, v12.16.0</span> </div> <p>See <a href="stream.html#stream_writable_cork"><code>writable.cork()</code></a>.</p> <h4><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#http_response_end_data_encoding_callback" id="http_response_end_data_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, <code>response.end()</code>, MUST be called on each response.</p> <p>If <code>data</code> is specified, it is similar in effect to calling <a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p> <p>If <code>callback</code> is specified, it will be called when the response stream is finished.</p> <h4><code>response.finished</code><span><a class="mark" href="#http_response_finished" id="http_response_finished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.0.2</span><span>Deprecated since: v13.4.0, v12.16.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_response_writableended"><code>response.writableEnded</code></a>.</div><p></p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>response.finished</code> property will be <code>true</code> if <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> has been called.</p> <h4><code>response.flushHeaders()</code><span><a class="mark" href="#http_response_flushheaders" id="http_response_flushheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <p>Flushes the response headers. See also: <a href="#http_request_flushheaders"><code>request.flushHeaders()</code></a>.</p> <h4><code>response.getHeader(name)</code><span><a class="mark" href="#http_response_getheader_name" id="http_response_getheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Reads out a header that's already been queued but not sent to the client. The name is case-insensitive. The type of the return value depends on the arguments provided to <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>.</p> <pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>); response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body)); response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]); <span class="hljs-keyword">const</span> contentType = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'content-type'</span>); <span class="hljs-comment">// contentType is 'text/html'</span> <span class="hljs-keyword">const</span> contentLength = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>); <span class="hljs-comment">// contentLength is of type number</span> <span class="hljs-keyword">const</span> setCookie = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'set-cookie'</span>); <span class="hljs-comment">// setCookie is of type string[]</span></code></pre> <h4><code>response.getHeaderNames()</code><span><a class="mark" href="#http_response_getheadernames" id="http_response_getheadernames">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.</p> <pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>); response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]); <span class="hljs-keyword">const</span> headerNames = response.<span class="hljs-title function_">getHeaderNames</span>(); <span class="hljs-comment">// headerNames === ['foo', 'set-cookie']</span></code></pre> <h4><code>response.getHeaders()</code><span><a class="mark" href="#http_response_getheaders" id="http_response_getheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.</p> <p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em> prototypically inherit from the JavaScript <code>Object</code>. This means that typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and <em>will not work</em>.</p> <pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>); response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]); <span class="hljs-keyword">const</span> headers = response.<span class="hljs-title function_">getHeaders</span>(); <span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code></pre> <h4><code>response.hasHeader(name)</code><span><a class="mark" href="#http_response_hasheader_name" id="http_response_hasheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the outgoing headers. The header name matching is case-insensitive.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = response.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code></pre> <h4><code>response.headersSent</code><span><a class="mark" href="#http_response_headerssent" id="http_response_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Boolean (read-only). True if headers were sent, false otherwise.</p> <h4><code>response.removeHeader(name)</code><span><a class="mark" href="#http_response_removeheader_name" id="http_response_removeheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that's queued for implicit sending.</p> <pre><code class="language-js">response.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code></pre> <h4><code>response.sendDate</code><span><a class="mark" href="#http_response_senddate" id="http_response_senddate">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.</p> <p>This should only be disabled for testing; HTTP requires the Date header in responses.</p> <h4><code>response.setHeader(name, value)</code><span><a class="mark" href="#http_response_setheader_name_value" id="http_response_setheader_name_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Returns the response object.</p> <p>Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> may return non-string values. However, the non-string values will be converted to strings for network transmission. The same response object is returned to the caller, to enable call chaining.</p> <pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);</code></pre> <p>or</p> <pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>); res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>); res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>); });</code></pre> <p>If <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead of <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>.</p> <h4><code>response.setTimeout(msecs[, callback])</code><span><a class="mark" href="#http_response_settimeout_msecs_callback" id="http_response_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Sets the Socket's timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h4><code>response.socket</code><span><a class="mark" href="#http_response_socket" id="http_response_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. After <code>response.end()</code>, the property is nulled.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { <span class="hljs-keyword">const</span> ip = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>; <span class="hljs-keyword">const</span> port = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>; res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>); }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code></pre> <p>This property is guaranteed to be an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specified a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4><code>response.statusCode</code><span><a class="mark" href="#http_response_statuscode" id="http_response_statuscode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>200</code></li> </ul> <p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status code that will be sent to the client when the headers get flushed.</p> <pre><code class="language-js">response.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>;</code></pre> <p>After response header was sent to the client, this property indicates the status code which was sent out.</p> <h4><code>response.statusMessage</code><span><a class="mark" href="#http_response_statusmessage" id="http_response_statusmessage">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as <code>undefined</code> then the standard message for the status code will be used.</p> <pre><code class="language-js">response.<span class="hljs-property">statusMessage</span> = <span class="hljs-string">'Not found'</span>;</code></pre> <p>After response header was sent to the client, this property indicates the status message which was sent out.</p> <h4><code>response.uncork()</code><span><a class="mark" href="#http_response_uncork" id="http_response_uncork">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.2.0, v12.16.0</span> </div> <p>See <a href="stream.html#stream_writable_uncork"><code>writable.uncork()</code></a>.</p> <h4><code>response.writableEnded</code><span><a class="mark" href="#http_response_writableended" id="http_response_writableended">#</a></span></h4> <div class="api_metadata"> <span>Added in: v12.9.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> after <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> has been called. This property does not indicate whether the data has been flushed, for this use <a href="#http_response_writablefinished"><code>response.writableFinished</code></a> instead.</p> <h4><code>response.writableFinished</code><span><a class="mark" href="#http_response_writablefinished" id="http_response_writablefinished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v12.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if all data has been flushed to the underlying system, immediately before the <a href="#http_event_finish"><code>'finish'</code></a> event is emitted.</p> <h4><code>response.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#http_response_write_chunk_encoding_callback" id="http_response_write_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.29</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If this method is called and <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> has not been called, it will switch to implicit header mode and flush the implicit headers.</p> <p>This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.</p> <p>In the <code>http</code> module, the response body is omitted when the request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses <em>must not</em> include a message body.</p> <p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string, the second parameter specifies how to encode it into a byte stream. <code>callback</code> will be called when this chunk of data is flushed.</p> <p>This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.</p> <p>The first time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered header information and the first chunk of the body to the client. The second time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <h4><code>response.writeContinue()</code><span><a class="mark" href="#http_response_writecontinue" id="http_response_writecontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <p>Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the <a href="#http_event_checkcontinue"><code>'checkContinue'</code></a> event on <code>Server</code>.</p> <h4><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#http_response_writehead_statuscode_statusmessage_headers" id="http_response_writehead_statuscode_statusmessage_headers">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.14.0</td> <td><p>Allow passing headers as an array.</p></td></tr> <tr><td>v11.10.0, v10.17.0</td> <td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr> <tr><td>v5.11.0, v4.4.5</td> <td><p>A <code>RangeError</code> is thrown if <code>statusCode</code> is not a number in the range <code>[100, 999]</code>.</p></td></tr> <tr><td>v0.1.30</td> <td><p><span>Added in: v0.1.30</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> <li>Returns: <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Sends a response header to the request. The status code is a 3-digit HTTP status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers. Optionally one can give a human-readable <code>statusMessage</code> as the second argument.</p> <p><code>headers</code> may be an <code>Array</code> where the keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. The array is in the same format as <code>request.rawHeaders</code>.</p> <p>Returns a reference to the <code>ServerResponse</code>, so that calls can be chained.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> body = <span class="hljs-string">'hello world'</span>; response .<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body), <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> }) .<span class="hljs-title function_">end</span>(body);</code></pre> <p>This method must only be called once on a message and it must be called before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p> <p>If <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> are called before calling this, the implicit/mutable headers will be calculated and call this function.</p> <p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <p>If this method is called and <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead.</p> <pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>); res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>); res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>); });</code></pre> <p><code>Content-Length</code> is given in bytes, not characters. Use <a href="buffer.html#buffer_static_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes. Node.js does not check whether <code>Content-Length</code> and the length of the body which has been transmitted are equal or not.</p> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4><code>response.writeProcessing()</code><span><a class="mark" href="#http_response_writeprocessing" id="http_response_writeprocessing">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.</p> </section><section><h3>Class: <code>http.IncomingMessage</code><span><a class="mark" href="#http_class_http_incomingmessage" id="http_class_http_incomingmessage">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v13.1.0, v12.16.0</td> <td><p>The <code>readableHighWaterMark</code> value mirrors that of the socket.</p></td></tr> <tr><td>v0.1.17</td> <td><p><span>Added in: v0.1.17</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Extends: <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>An <code>IncomingMessage</code> object is created by <a href="#http_class_http_server"><code>http.Server</code></a> or <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <a href="#http_event_request"><code>'request'</code></a> and <a href="#http_event_response"><code>'response'</code></a> event respectively. It may be used to access response status, headers and data.</p> <h4>Event: <code>'aborted'</code><span><a class="mark" href="#http_event_aborted" id="http_event_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <p>Emitted when the request has been aborted.</p> <h4>Event: <code>'close'</code><span><a class="mark" href="#http_event_close_2" id="http_event_close_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.2</span> </div> <p>Indicates that the underlying connection was closed.</p> <h4><code>message.aborted</code><span><a class="mark" href="#http_message_aborted" id="http_message_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>message.aborted</code> property will be <code>true</code> if the request has been aborted.</p> <h4><code>message.complete</code><span><a class="mark" href="#http_message_complete" id="http_message_complete">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>message.complete</code> property will be <code>true</code> if a complete HTTP message has been received and successfully parsed.</p> <p>This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>({ <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>, <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span> }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { res.<span class="hljs-title function_">resume</span>(); res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-keyword">if</span> (!res.<span class="hljs-property">complete</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>( <span class="hljs-string">'The connection was terminated while the message was still being sent'</span>); }); });</code></pre> <h4><code>message.destroy([error])</code><span><a class="mark" href="#http_message_destroy_error" id="http_message_destroy_error">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.5.0</td> <td><p>The function returns <code>this</code> for consistency with other Readable streams.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Calls <code>destroy()</code> on the socket that received the <code>IncomingMessage</code>. If <code>error</code> is provided, an <code>'error'</code> event is emitted on the socket and <code>error</code> is passed as an argument to any listeners on the event.</p> <h4><code>message.headers</code><span><a class="mark" href="#http_message_headers" id="http_message_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.5</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response headers object.</p> <p>Key-value pairs of header names and values. Header names are lower-cased.</p> <pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// { 'user-agent': 'curl/7.22.0',</span> <span class="hljs-comment">// host: '127.0.0.1:8000',</span> <span class="hljs-comment">// accept: '*/*' }</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headers</span>);</code></pre> <p>Duplicates in raw headers are handled in the following ways, depending on the header name:</p> <ul> <li>Duplicates of <code>age</code>, <code>authorization</code>, <code>content-length</code>, <code>content-type</code>, <code>etag</code>, <code>expires</code>, <code>from</code>, <code>host</code>, <code>if-modified-since</code>, <code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>referer</code>, <code>retry-after</code>, <code>server</code>, or <code>user-agent</code> are discarded.</li> <li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li> <li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li> <li>For all other headers, the values are joined together with ', '.</li> </ul> <h4><code>message.httpVersion</code><span><a class="mark" href="#http_message_httpversion" id="http_message_httpversion">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either <code>'1.1'</code> or <code>'1.0'</code>.</p> <p>Also <code>message.httpVersionMajor</code> is the first integer and <code>message.httpVersionMinor</code> is the second.</p> <h4><code>message.method</code><span><a class="mark" href="#http_message_method" id="http_message_method">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p> <p>The request method as a string. Read only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p> <h4><code>message.rawHeaders</code><span><a class="mark" href="#http_message_rawheaders" id="http_message_rawheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response headers list exactly as they were received.</p> <p>The keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.</p> <p>Header names are not lowercased, and duplicates are not merged.</p> <pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// [ 'user-agent',</span> <span class="hljs-comment">// 'this is invalid because there can be only one',</span> <span class="hljs-comment">// 'User-Agent',</span> <span class="hljs-comment">// 'curl/7.22.0',</span> <span class="hljs-comment">// 'Host',</span> <span class="hljs-comment">// '127.0.0.1:8000',</span> <span class="hljs-comment">// 'ACCEPT',</span> <span class="hljs-comment">// '*/*' ]</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">rawHeaders</span>);</code></pre> <h4><code>message.rawTrailers</code><span><a class="mark" href="#http_message_rawtrailers" id="http_message_rawtrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response trailer keys and values exactly as they were received. Only populated at the <code>'end'</code> event.</p> <h4><code>message.setTimeout(msecs[, callback])</code><span><a class="mark" href="#http_message_settimeout_msecs_callback" id="http_message_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> </ul> <p>Calls <code>message.socket.setTimeout(msecs, callback)</code>.</p> <h4><code>message.socket</code><span><a class="mark" href="#http_message_socket" id="http_message_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>The <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection.</p> <p>With HTTPS support, use <a href="tls.html#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's authentication details.</p> <p>This property is guaranteed to be an instance of the <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> class, a subclass of <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a>, unless the user specified a socket type other than <a href="net.html#net_class_net_socket" class="type"><net.Socket></a>.</p> <h4><code>message.statusCode</code><span><a class="mark" href="#http_message_statuscode" id="http_message_statuscode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong></p> <p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p> <h4><code>message.statusMessage</code><span><a class="mark" href="#http_message_statusmessage" id="http_message_statusmessage">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.10</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong></p> <p>The HTTP response status message (reason phrase). E.G. <code>OK</code> or <code>Internal Server Error</code>.</p> <h4><code>message.trailers</code><span><a class="mark" href="#http_message_trailers" id="http_message_trailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p> <h4><code>message.url</code><span><a class="mark" href="#http_message_url" id="http_message_url">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p> <p>Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:</p> <pre><code class="language-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/status?name=ryan</span> <span class="hljs-meta">HTTP/1.1</span> <span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>text/plain</code></pre> <p>To parse the URL into its parts:</p> <pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(request.<span class="hljs-property">url</span>, <span class="hljs-string">`http://<span class="hljs-subst">${request.headers.host}</span>`</span>);</code></pre> <p>When <code>request.url</code> is <code>'/status?name=ryan'</code> and <code>request.headers.host</code> is <code>'localhost:3000'</code>:</p> <pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node</span> <span class="hljs-meta">> </span><span class="language-bash">new URL(request.url, `http://<span class="hljs-variable">${request.headers.host}</span>`)</span> URL { href: 'http://localhost:3000/status?name=ryan', origin: 'http://localhost:3000', protocol: 'http:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/status', search: '?name=ryan', searchParams: URLSearchParams { 'name' => 'ryan' }, hash: '' }</code></pre> </section><section><h3>Class: <code>http.OutgoingMessage</code><span><a class="mark" href="#http_class_http_outgoingmessage" id="http_class_http_outgoingmessage">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li>Extends: <a href="stream.html#stream_stream" class="type"><Stream></a></li> </ul> <p>This class serves as the parent class of <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and <a href="#http_class_http_serverresponse"><code>http.ServerResponse</code></a>. It is an abstract of outgoing message from the perspective of the participants of HTTP transaction.</p> <h4>Event: <code>drain</code><span><a class="mark" href="#http_event_drain" id="http_event_drain">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <p>Emitted when the buffer of the message is free again.</p> <h4>Event: <code>finish</code><span><a class="mark" href="#http_event_finish_1" id="http_event_finish_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <p>Emitted when the transmission is finished successfully.</p> <h4>Event: <code>prefinish</code><span><a class="mark" href="#http_event_prefinish" id="http_event_prefinish">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.6</span> </div> <p>Emitted when <code>outgoingMessage.end</code> was called. When the event is emitted, all data has been processed but not necessarily completely flushed.</p> <h4><code>outgoingMessage.addTrailers(headers)</code><span><a class="mark" href="#http_outgoingmessage_addtrailers_headers" id="http_outgoingmessage_addtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Adds HTTP trailers (headers but at the end of the message) to the message.</p> <p>Trailers are <strong>only</strong> be emitted if the message is chunked encoded. If not, the trailer will be silently discarded.</p> <p>HTTP requires the <code>Trailer</code> header to be sent to emit trailers, with a list of header fields in its value, e.g.</p> <pre><code class="language-js">message.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>, <span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> }); message.<span class="hljs-title function_">write</span>(fileData); message.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> }); message.<span class="hljs-title function_">end</span>();</code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <code>TypeError</code> being thrown.</p> <h4><code>outgoingMessage.connection</code><span><a class="mark" href="#http_outgoingmessage_connection" id="http_outgoingmessage_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v14.17.1</span> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#http_outgoingmessage_socket"><code>outgoingMessage.socket</code></a> instead.</div><p></p> <p>Aliases of <code>outgoingMessage.socket</code></p> <h4><code>outgoingMessage.cork()</code><span><a class="mark" href="#http_outgoingmessage_cork" id="http_outgoingmessage_cork">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.0.0</span> </div> <p>See <a href="stream.html#stream_writable_cork"><code>writable.cork()</code></a>.</p> <h4><code>outgoingMessage.destroy([error])</code><span><a class="mark" href="#http_outgoingmessage_destroy_error" id="http_outgoingmessage_destroy_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Optional, an error to emit with <code>error</code> event</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well.</p> <h4><code>outgoingMessage.end(chunk[, encoding][, callback])</code><span><a class="mark" href="#http_outgoingmessage_end_chunk_encoding_callback" id="http_outgoingmessage_end_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v0.11.6</td> <td><p>add <code>callback</code> argument.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional, <strong>Default</strong>: <code>utf-8</code></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Finishes the outgoing message. If any parts of the body are unsent, it will flush them to the underlying system. If the message is chunked, it will send the terminating chunk <code>0\r\n\r\n</code>, and send the trailer (if any).</p> <p>If <code>chunk</code> is specified, it is equivalent to call <code>outgoingMessage.write(chunk, encoding)</code>, followed by <code>outgoingMessage.end(callback)</code>.</p> <p>If <code>callback</code> is provided, it will be called when the message is finished. (equivalent to the callback to event <code>finish</code>)</p> <h4><code>outgoingMessage.flushHeaders()</code><span><a class="mark" href="#http_outgoingmessage_flushheaders" id="http_outgoingmessage_flushheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <p>Compulsorily flushes the message headers</p> <p>For efficiency reason, Node.js normally buffers the message headers until <code>outgoingMessage.end()</code> is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet.</p> <p>It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. <code>outgoingMessage.flushHeaders()</code> bypasses the optimization and kickstarts the request.</p> <h4><code>outgoingMessage.getHeader(name)</code><span><a class="mark" href="#http_outgoingmessage_getheader_name" id="http_outgoingmessage_getheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of header</li> <li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Gets the value of HTTP header with the given name. If such a name doesn't exist in message, it will be <code>undefined</code>.</p> <h4><code>outgoingMessage.getHeaderNames()</code><span><a class="mark" href="#http_outgoingmessage_getheadernames" id="http_outgoingmessage_getheadernames">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array of names of headers of the outgoing outgoingMessage. All names are lowercase.</p> <h4><code>outgoingMessage.getHeaders()</code><span><a class="mark" href="#http_outgoingmessage_getheaders" id="http_outgoingmessage_getheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.</p> <p>The object returned by the <code>outgoingMessage.getHeaders()</code> method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and will not work.</p> <pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>); outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]); <span class="hljs-keyword">const</span> headers = outgoingMessage.<span class="hljs-title function_">getHeaders</span>(); <span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code></pre> <h4><code>outgoingMessage.hasHeader(name)</code><span><a class="mark" href="#http_outgoingmessage_hasheader_name" id="http_outgoingmessage_hasheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the outgoing headers. The header name is case-insensitive.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = outgoingMessage.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code></pre> <h4><code>outgoingMessage.headersSent</code><span><a class="mark" href="#http_outgoingmessage_headerssent" id="http_outgoingmessage_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Read-only. <code>true</code> if the headers were sent, otherwise <code>false</code>.</p> <h4><code>outgoingMessage.pipe()</code><span><a class="mark" href="#http_outgoingmessage_pipe" id="http_outgoingmessage_pipe">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <p>Overrides the pipe method of legacy <code>Stream</code> which is the parent class of <code>http.outgoingMessage</code>.</p> <p>Since <code>OutgoingMessage</code> should be a write-only stream, call this function will throw an <code>Error</code>. Thus, it disabled the pipe method it inherits from <code>Stream</code>.</p> <p>The User should not call this function directly.</p> <h4><code>outgoingMessage.removeHeader()</code><span><a class="mark" href="#http_outgoingmessage_removeheader" id="http_outgoingmessage_removeheader">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <p>Removes a header that is queued for implicit sending.</p> <pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code></pre> <h4><code>outgoingMessage.setHeader(name, value)</code><span><a class="mark" href="#http_outgoingmessage_setheader_name_value" id="http_outgoingmessage_setheader_name_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Header name</li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Header value</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Sets a single header value for the header object.</p> <h4><code>outgoingMessage.setTimeout(msesc[, callback])</code><span><a class="mark" href="#http_outgoingmessage_settimeout_msesc_callback" id="http_outgoingmessage_settimeout_msesc_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>msesc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional function to be called when a timeout</li> </ul> <p>occurs, Same as binding to the <code>timeout</code> event.</p> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Once a socket is associated with the message and is connected, <a href="net.html#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called with <code>msecs</code> as the first parameter.</p> <h4><code>outgoingMessage.socket</code><span><a class="mark" href="#http_outgoingmessage_socket" id="http_outgoingmessage_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Reference to the underlying socket. Usually, users will not want to access this property.</p> <p>After calling <code>outgoingMessage.end()</code>, this property will be nulled.</p> <h4><code>outgoingMessage.uncork()</code><span><a class="mark" href="#http_outgoingmessage_uncork" id="http_outgoingmessage_uncork">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.0.0</span> </div> <p>See <a href="stream.html#stream_writable_uncork"><code>writable.uncork()</code></a></p> <h4><code>outgoingMessage.writableCorked</code><span><a class="mark" href="#http_outgoingmessage_writablecorked" id="http_outgoingmessage_writablecorked">#</a></span></h4> <div class="api_metadata"> <span>Added in: v14.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>This <code>outgoingMessage.writableCorked</code> will return the time how many <code>outgoingMessage.cork()</code> have been called.</p> <h4><code>outgoingMessage.writableEnded</code><span><a class="mark" href="#http_outgoingmessage_writableended" id="http_outgoingmessage_writableended">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Readonly, <code>true</code> if <code>outgoingMessage.end()</code> has been called. Noted that this property does not reflect whether the data has been flush. For that purpose, use <code>message.writableFinished</code> instead.</p> <h4><code>outgoingMessage.writableFinished</code><span><a class="mark" href="#http_outgoingmessage_writablefinished" id="http_outgoingmessage_writablefinished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Readonly. <code>true</code> if all data has been flushed to the underlying system.</p> <h4><code>outgoingMessage.writableHighWaterMark</code><span><a class="mark" href="#http_outgoingmessage_writablehighwatermark" id="http_outgoingmessage_writablehighwatermark">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>This <code>outgoingMessage.writableHighWaterMark</code> will be the <code>highWaterMark</code> of underlying socket if socket exists. Else, it would be the default <code>highWaterMark</code>.</p> <p><code>highWaterMark</code> is the maximum amount of data that can be potentially buffered by the socket.</p> <h4><code>outgoingMessage.writableLength</code><span><a class="mark" href="#http_outgoingmessage_writablelength" id="http_outgoingmessage_writablelength">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Readonly, This <code>outgoingMessage.writableLength</code> contains the number of bytes (or objects) in the buffer ready to send.</p> <h4><code>outgoingMessage.writableObjectMode</code><span><a class="mark" href="#http_outgoingmessage_writableobjectmode" id="http_outgoingmessage_writableobjectmode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v13.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Readonly, always returns <code>false</code>.</p> <h4><code>outgoingMessage.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#http_outgoingmessage_write_chunk_encoding_callback" id="http_outgoingmessage_write_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v0.11.6</td> <td><p>add <code>callback</code> argument.</p></td></tr> <tr><td>v0.1.29</td> <td><p><span>Added in: v0.1.29</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default</strong>: <code>utf-8</code></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If this method is called and the header is not sent, it will call <code>this._implicitHeader</code> to flush implicit header. If the message should not have a body (indicated by <code>this._hasBody</code>), the call is ignored and <code>chunk</code> will not be sent. It could be useful when handling a particular message which must not include a body. e.g. response to <code>HEAD</code> request, <code>204</code> and <code>304</code> response.</p> <p><code>chunk</code> can be a string or a buffer. When <code>chunk</code> is a string, the <code>encoding</code> parameter specifies how to encode <code>chunk</code> into a byte stream. <code>callback</code> will be called when the <code>chunk</code> is flushed.</p> <p>If the message is transferred in chucked encoding (indicated by <code>this.chunkedEncoding</code>), <code>chunk</code> will be flushed as one chunk among a stream of chunks. Otherwise, it will be flushed as the body of message.</p> <p>This method handles the raw body of the HTTP message and has nothing to do with higher-level multi-part body encodings that may be used.</p> <p>If it is the first call to this method of a message, it will send the buffered header first, then flush the <code>chunk</code> as described above.</p> <p>The second and successive calls to this method will assume the data will be streamed and send the new data separately. It means that the response is buffered up to the first chunk of the body.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in the user memory. Event <code>drain</code> will be emitted when the buffer is free again.</p> </section><section><h3><code>http.METHODS</code><span><a class="mark" href="#http_http_methods" id="http_http_methods">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>A list of the HTTP methods that are supported by the parser.</p> </section><section><h3><code>http.STATUS_CODES</code><span><a class="mark" href="#http_http_status_codes" id="http_http_status_codes">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.22</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>A collection of all the standard HTTP response status codes, and the short description of each. For example, <code>http.STATUS_CODES[404] === 'Not Found'</code>.</p> </section><section><h3><code>http.createServer([options][, requestListener])</code><span><a class="mark" href="#http_http_createserver_options_requestlistener" id="http_http_createserver_options_requestlistener">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v13.3.0</td> <td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr> <tr><td>v13.8.0, v12.15.0, v10.19.0</td> <td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr> <tr><td>v9.6.0, v8.12.0</td> <td><p>The <code>options</code> argument is supported now.</p></td></tr> <tr><td>v0.1.13</td> <td><p><span>Added in: v0.1.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>IncomingMessage</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the <code>IncomingMessage</code> class to be used. Useful for extending the original <code>IncomingMessage</code>. <strong>Default:</strong> <code>IncomingMessage</code>.</li> <li><code>ServerResponse</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code> class to be used. Useful for extending the original <code>ServerResponse</code>. <strong>Default:</strong> <code>ServerResponse</code>.</li> <li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Use an insecure HTTP parser that accepts invalid HTTP headers when <code>true</code>. Using the insecure parser should be avoided. See <a href="cli.html#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information. <strong>Default:</strong> <code>false</code></li> <li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally overrides the value of <a href="cli.html#cli_max_http_header_size_size"><code>--max-http-header-size</code></a> for requests received by this server, i.e. the maximum length of request headers in bytes. <strong>Default:</strong> 16384 (16KB).</li> </ul> </li> <li> <p><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> </li> <li> <p>Returns: <a href="http.html#http_class_http_server" class="type"><http.Server></a></p> </li> </ul> <p>Returns a new instance of <a href="#http_class_http_server"><code>http.Server</code></a>.</p> <p>The <code>requestListener</code> is a function which is automatically added to the <a href="#http_event_request"><code>'request'</code></a> event.</p> <pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><pre><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-comment">// Create a local server to receive data from</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span> })); }); server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code></pre><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-comment">// Create a local server to receive data from</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(); <span class="hljs-comment">// Listen to the request event</span> server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'request'</span>, <span class="hljs-function">(<span class="hljs-params">request, res</span>) =></span> { res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span> })); }); server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code></pre> </section><section><h3><code>http.get(options[, callback])</code><span><a class="mark" href="#http_http_get_options_callback" id="http_http_get_options_callback">#</a></span></h3> </section><section><h3><code>http.get(url[, options][, callback])</code><span><a class="mark" href="#http_http_get_url_options_callback" id="http_http_get_url_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Accepts the same <code>options</code> as <a href="#http_http_request_options_callback"><code>http.request()</code></a>, with the <code>method</code> always set to <code>GET</code>. Properties that are inherited from the prototype are ignored.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http.html#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and <a href="#http_http_request_options_callback"><code>http.request()</code></a> is that it sets the method to GET and calls <code>req.end()</code> automatically. The callback must take care to consume the response data for reasons stated in <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> section.</p> <p>The <code>callback</code> is invoked with a single argument that is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p> <p>JSON fetching example:</p> <pre><code class="language-js">http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8000/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-keyword">const</span> { statusCode } = res; <span class="hljs-keyword">const</span> contentType = res.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-type'</span>]; <span class="hljs-keyword">let</span> error; <span class="hljs-comment">// Any 2xx status code signals a successful response but</span> <span class="hljs-comment">// here we're only checking for 200.</span> <span class="hljs-keyword">if</span> (statusCode !== <span class="hljs-number">200</span>) { error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Request Failed.\n'</span> + <span class="hljs-string">`Status Code: <span class="hljs-subst">${statusCode}</span>`</span>); } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/^application\/json/</span>.<span class="hljs-title function_">test</span>(contentType)) { error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Invalid content-type.\n'</span> + <span class="hljs-string">`Expected application/json but received <span class="hljs-subst">${contentType}</span>`</span>); } <span class="hljs-keyword">if</span> (error) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">message</span>); <span class="hljs-comment">// Consume response data to free up memory</span> res.<span class="hljs-title function_">resume</span>(); <span class="hljs-keyword">return</span>; } res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-keyword">let</span> rawData = <span class="hljs-string">''</span>; res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { rawData += chunk; }); res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">const</span> parsedData = <span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">parse</span>(rawData); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(parsedData); } <span class="hljs-keyword">catch</span> (e) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>); } }); }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Got error: <span class="hljs-subst">${e.message}</span>`</span>); }); <span class="hljs-comment">// Create a local server to receive data from</span> <span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> }); res.<span class="hljs-title function_">end</span>(<span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span> })); }); server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code></pre> </section><section><h3><code>http.globalAgent</code><span><a class="mark" href="#http_http_globalagent" id="http_http_globalagent">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><a href="http.html#http_class_http_agent" class="type"><http.Agent></a></li> </ul> <p>Global instance of <code>Agent</code> which is used as the default for all HTTP client requests.</p> </section><section><h3><code>http.maxHeaderSize</code><span><a class="mark" href="#http_http_maxheadersize" id="http_http_maxheadersize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v11.6.0, v10.15.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 8KB. Configurable using the <a href="cli.html#cli_max_http_header_size_size"><code>--max-http-header-size</code></a> CLI option.</p> <p>This can be overridden for servers and client requests by passing the <code>maxHeaderSize</code> option.</p> </section><section><h3><code>http.request(options[, callback])</code><span><a class="mark" href="#http_http_request_options_callback" id="http_http_request_options_callback">#</a></span></h3> </section><section><h3><code>http.request(url[, options][, callback])</code><span><a class="mark" href="#http_http_request_url_options_callback" id="http_http_request_url_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.18.0</td> <td><p>When using a <code>URL</code> object parsed username and password will now be properly URI decoded.</p></td></tr> <tr><td>v14.17.0</td> <td><p>It is possible to abort a request with an AbortSignal.</p></td></tr> <tr><td>v13.3.0</td> <td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr> <tr><td>v13.8.0, v12.15.0, v10.19.0</td> <td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>agent</code> <a href="http.html#http_class_http_agent" class="type"><http.Agent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Controls <a href="#http_class_http_agent"><code>Agent</code></a> behavior. Possible values: <ul> <li><code>undefined</code> (default): use <a href="#http_http_globalagent"><code>http.globalAgent</code></a> for this host and port.</li> <li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li> <li><code>false</code>: causes a new <code>Agent</code> with default values to be used.</li> </ul> </li> <li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Basic authentication i.e. <code>'user:password'</code> to compute an Authorization header.</li> <li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that produces a socket/stream to use for the request when the <code>agent</code> option is not used. This can be used to avoid creating a custom <code>Agent</code> class just to override the default <code>createConnection</code> function. See <a href="#http_agent_createconnection_options_callback"><code>agent.createConnection()</code></a> for more details. Any <a href="stream.html#stream_class_stream_duplex"><code>Duplex</code></a> stream is a valid return value.</li> <li><code>defaultPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Default port for the protocol. <strong>Default:</strong> <code>agent.defaultPort</code> if an <code>Agent</code> is used, else <code>undefined</code>.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> IP address family to use when resolving <code>host</code> or <code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and v6 will be used.</li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing request headers.</li> <li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional <a href="dns.html#dns_supported_getaddrinfo_flags"><code>dns.lookup()</code> hints</a>.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the request to. <strong>Default:</strong> <code>'localhost'</code>.</li> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Alias for <code>host</code>. To support <a href="url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>, <code>hostname</code> will be used if both <code>host</code> and <code>hostname</code> are specified.</li> <li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Use an insecure HTTP parser that accepts invalid HTTP headers when <code>true</code>. Using the insecure parser should be avoided. See <a href="cli.html#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information. <strong>Default:</strong> <code>false</code></li> <li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections.</li> <li><code>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Local port to connect from.</li> <li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> <li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally overrides the value of <a href="cli.html#cli_max_http_header_size_size"><code>--max-http-header-size</code></a> for requests received from the server, i.e. the maximum length of response headers in bytes. <strong>Default:</strong> 16384 (16KB).</li> <li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string specifying the HTTP request method. <strong>Default:</strong> <code>'GET'</code>.</li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Request path. Should include query string if any. E.G. <code>'/index.html?page=12'</code>. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. <strong>Default:</strong> <code>'/'</code>.</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server. <strong>Default:</strong> <code>defaultPort</code> if set, else <code>80</code>.</li> <li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Protocol to use. <strong>Default:</strong> <code>'http:'</code>.</li> <li><code>setHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>: Specifies whether or not to automatically add the <code>Host</code> header. Defaults to <code>true</code>.</li> <li><code>socketPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Unix Domain Socket (cannot be used if one of <code>host</code> or <code>port</code> is specified, those specify a TCP Socket).</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.</li> <li><code>signal</code> <a href="globals.html#globals_class_abortsignal" class="type"><AbortSignal></a>: An AbortSignal that may be used to abort an ongoing request.</li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http.html#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.</p> <p><code>url</code> can be a string or a <a href="url.html#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>url</code> is a string, it is automatically parsed with <a href="url.html#url_new_url_input_base"><code>new URL()</code></a>. If it is a <a href="url.html#url_the_whatwg_url_api"><code>URL</code></a> object, it will be automatically converted to an ordinary <code>options</code> object.</p> <p>If both <code>url</code> and <code>options</code> are specified, the objects are merged, with the <code>options</code> properties taking precedence.</p> <p>The optional <code>callback</code> parameter will be added as a one-time listener for the <a href="#http_event_response"><code>'response'</code></a> event.</p> <p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> class. The <code>ClientRequest</code> instance is a writable stream. If one needs to upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">const</span> postData = <span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">stringify</span>({ <span class="hljs-string">'msg'</span>: <span class="hljs-string">'Hello World!'</span> }); <span class="hljs-keyword">const</span> options = { <span class="hljs-attr">hostname</span>: <span class="hljs-string">'www.google.com'</span>, <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'/upload'</span>, <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>, <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>, <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(postData) } }; <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`STATUS: <span class="hljs-subst">${res.statusCode}</span>`</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`HEADERS: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(res.headers)}</span>`</span>); res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`BODY: <span class="hljs-subst">${chunk}</span>`</span>); }); res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'No more data in response.'</span>); }); }); req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`problem with request: <span class="hljs-subst">${e.message}</span>`</span>); }); <span class="hljs-comment">// Write data to request body</span> req.<span class="hljs-title function_">write</span>(postData); req.<span class="hljs-title function_">end</span>();</code></pre> <p>In the example <code>req.end()</code> was called. With <code>http.request()</code> one must always call <code>req.end()</code> to signify the end of the request - even if there is no data being written to the request body.</p> <p>If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an <code>'error'</code> event is emitted on the returned request object. As with all <code>'error'</code> events, if no listeners are registered the error will be thrown.</p> <p>There are a few special headers that should be noted.</p> <ul> <li> <p>Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.</p> </li> <li> <p>Sending a 'Content-Length' header will disable the default chunked encoding.</p> </li> <li> <p>Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the <code>'continue'</code> event should be set. See RFC 2616 Section 8.2.3 for more information.</p> </li> <li> <p>Sending an Authorization header will override using the <code>auth</code> option to compute basic authentication.</p> </li> </ul> <p>Example using a <a href="url.html#url_the_whatwg_url_api"><code>URL</code></a> as <code>options</code>:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> options = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://abc:xyz@example.com'</span>); <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-comment">// ...</span> });</code></pre> <p>In a successful request, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li><code>'response'</code> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object (<code>'data'</code> will not be emitted at all if the response body is empty, for instance, in most redirects)</li> <li><code>'end'</code> on the <code>res</code> object</li> </ul> </li> <li><code>'close'</code></li> </ul> <p>In the case of a connection error, the following events will be emitted:</p> <ul> <li><code>'socket'</code></li> <li><code>'error'</code></li> <li><code>'close'</code></li> </ul> <p>In the case of a premature connection close before the response is received, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code <code>'ECONNRESET'</code></li> <li><code>'close'</code></li> </ul> <p>In the case of a premature connection close after the response is received, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li><code>'response'</code> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object</li> </ul> </li> <li>(connection closed here)</li> <li><code>'aborted'</code> on the <code>res</code> object</li> <li><code>'close'</code></li> <li><code>'close'</code> on the <code>res</code> object</li> </ul> <p>If <code>req.destroy()</code> is called before a socket is assigned, the following events will be emitted in the following order:</p> <ul> <li>(<code>req.destroy()</code> called here)</li> <li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code <code>'ECONNRESET'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.destroy()</code> is called before the connection succeeds, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li>(<code>req.destroy()</code> called here)</li> <li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code <code>'ECONNRESET'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.destroy()</code> is called after the response is received, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li><code>'response'</code> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object</li> </ul> </li> <li>(<code>req.destroy()</code> called here)</li> <li><code>'aborted'</code> on the <code>res</code> object</li> <li><code>'close'</code></li> <li><code>'close'</code> on the <code>res</code> object</li> </ul> <p>If <code>req.abort()</code> is called before a socket is assigned, the following events will be emitted in the following order:</p> <ul> <li>(<code>req.abort()</code> called here)</li> <li><code>'abort'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.abort()</code> is called before the connection succeeds, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li>(<code>req.abort()</code> called here)</li> <li><code>'abort'</code></li> <li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code <code>'ECONNRESET'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.abort()</code> is called after the response is received, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li><code>'response'</code> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object</li> </ul> </li> <li>(<code>req.abort()</code> called here)</li> <li><code>'abort'</code></li> <li><code>'aborted'</code> on the <code>res</code> object</li> <li><code>'close'</code></li> <li><code>'close'</code> on the <code>res</code> object</li> </ul> <p>Setting the <code>timeout</code> option or using the <code>setTimeout()</code> function will not abort the request or do anything besides add a <code>'timeout'</code> event.</p> <p>Passing an <code>AbortSignal</code> and then calling <code>abort</code> on the corresponding <code>AbortController</code> will behave the same way as calling <code>.destroy()</code> on the request itself.</p> </section><section><h3><code>http.validateHeaderName(name)</code><span><a class="mark" href="#http_http_validateheadername_name" id="http_http_validateheadername_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v14.3.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Performs the low-level validations on the provided <code>name</code> that are done when <code>res.setHeader(name, value)</code> is called.</p> <p>Passing illegal value as <code>name</code> will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown, identified by <code>code: 'ERR_INVALID_HTTP_TOKEN'</code>.</p> <p>It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers. Examples:</p> <p>Example:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { validateHeaderName } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">try</span> { <span class="hljs-title function_">validateHeaderName</span>(<span class="hljs-string">''</span>); } <span class="hljs-keyword">catch</span> (err) { err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>; <span class="hljs-comment">// --> true</span> err.<span class="hljs-property">code</span>; <span class="hljs-comment">// --> 'ERR_INVALID_HTTP_TOKEN'</span> err.<span class="hljs-property">message</span>; <span class="hljs-comment">// --> 'Header name must be a valid HTTP token [""]'</span> }</code></pre> </section><section><h3><code>http.validateHeaderValue(name, value)</code><span><a class="mark" href="#http_http_validateheadervalue_name_value" id="http_http_validateheadervalue_name_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v14.3.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Performs the low-level validations on the provided <code>value</code> that are done when <code>res.setHeader(name, value)</code> is called.</p> <p>Passing illegal value as <code>value</code> will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <ul> <li>Undefined value error is identified by <code>code: 'ERR_HTTP_INVALID_HEADER_VALUE'</code>.</li> <li>Invalid value character error is identified by <code>code: 'ERR_INVALID_CHAR'</code>.</li> </ul> <p>It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.</p> <p>Examples:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { validateHeaderValue } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); <span class="hljs-keyword">try</span> { <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-literal">undefined</span>); } <span class="hljs-keyword">catch</span> (err) { err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>; <span class="hljs-comment">// --> true</span> err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_HTTP_INVALID_HEADER_VALUE'</span>; <span class="hljs-comment">// --> true</span> err.<span class="hljs-property">message</span>; <span class="hljs-comment">// --> 'Invalid value "undefined" for header "x-my-header"'</span> } <span class="hljs-keyword">try</span> { <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-string">'o蕣m瑟伞蓹'</span>); } <span class="hljs-keyword">catch</span> (err) { err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>; <span class="hljs-comment">// --> true</span> err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_INVALID_CHAR'</span>; <span class="hljs-comment">// --> true</span> err.<span class="hljs-property">message</span>; <span class="hljs-comment">// --> 'Invalid character in header content ["x-my-header"]'</span> }</code></pre></section> <!-- API END --> </div> </div> </div> <script> 'use strict'; { const kCustomPreference = 'customDarkTheme'; const userSettings = sessionStorage.getItem(kCustomPreference); const themeToggleButton = document.getElementById('theme-toggle-btn'); if (userSettings === null && window.matchMedia) { const mq = window.matchMedia('(prefers-color-scheme: dark)'); if ('onchange' in mq) { function mqChangeListener(e) { document.body.classList.toggle('dark-mode', e.matches); } mq.addEventListener('change', mqChangeListener); if (themeToggleButton) { themeToggleButton.addEventListener('click', function() { mq.removeEventListener('change', mqChangeListener); }, { once: true }); } } if (mq.matches) { document.body.classList.add('dark-mode'); } } else if (userSettings === 'true') { document.body.classList.add('dark-mode'); } if (themeToggleButton) { themeToggleButton.hidden = false; themeToggleButton.addEventListener('click', function() { sessionStorage.setItem( kCustomPreference, document.body.classList.toggle('dark-mode') ); }); } } </script> </body> </html>