- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- sqlite 轻型数据库
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v25.3.0 文档
- Node.js v25.3.0
-
目录
- 超文本传输协议
- 类:
http.Agent - 类:
http.ClientRequest- 事件:
'abort' - 事件:
'close' - 事件:
'connect' - 事件:
'continue' - 事件:
'finish' - 事件:
'information' - 事件:
'response' - 事件:
'socket' - 事件:
'timeout' - 事件:
'upgrade' request.abort()request.abortedrequest.connectionrequest.cork()request.end([data[, encoding]][, callback])request.destroy([error])request.finishedrequest.flushHeaders()request.getHeader(name)request.getHeaderNames()request.getHeaders()request.getRawHeaderNames()request.hasHeader(name)request.maxHeadersCountrequest.pathrequest.methodrequest.hostrequest.protocolrequest.removeHeader(name)request.reusedSocketrequest.setHeader(name, value)request.setNoDelay([noDelay])request.setSocketKeepAlive([enable][, initialDelay])request.setTimeout(timeout[, callback])request.socketrequest.uncork()request.writableEndedrequest.writableFinishedrequest.write(chunk[, encoding][, callback])
- 事件:
- 类:
http.Server- 事件:
'checkContinue' - 事件:
'checkExpectation' - 事件:
'clientError' - 事件:
'close' - 事件:
'connect' - 事件:
'connection' - 事件:
'dropRequest' - 事件:
'request' - 事件:
'upgrade' server.close([callback])server.closeAllConnections()server.closeIdleConnections()server.headersTimeoutserver.listen()server.listeningserver.maxHeadersCountserver.requestTimeoutserver.setTimeout([msecs][, callback])server.maxRequestsPerSocketserver.timeoutserver.keepAliveTimeoutserver.keepAliveTimeoutBufferserver[Symbol.asyncDispose]()
- 事件:
- 类:
http.ServerResponse- 事件:
'close' - 事件:
'finish' response.addTrailers(headers)response.connectionresponse.cork()response.end([data[, encoding]][, callback])response.finishedresponse.flushHeaders()response.getHeader(name)response.getHeaderNames()response.getHeaders()response.hasHeader(name)response.headersSentresponse.removeHeader(name)response.reqresponse.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.strictContentLengthresponse.uncork()response.writableEndedresponse.writableFinishedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeEarlyHints(hints[, callback])response.writeHead(statusCode[, statusMessage][, headers])response.writeProcessing()
- 事件:
- 类:
http.IncomingMessage- 事件:
'aborted' - 事件:
'close' message.abortedmessage.completemessage.connectionmessage.destroy([error])message.headersmessage.headersDistinctmessage.httpVersionmessage.methodmessage.rawHeadersmessage.rawTrailersmessage.setTimeout(msecs[, callback])message.socketmessage.statusCodemessage.statusMessagemessage.trailersmessage.trailersDistinctmessage.url
- 事件:
- 类:
http.OutgoingMessage- 事件:
'drain' - 事件:
'finish' - 事件:
'prefinish' outgoingMessage.addTrailers(headers)outgoingMessage.appendHeader(name, value)outgoingMessage.connectionoutgoingMessage.cork()outgoingMessage.destroy([error])outgoingMessage.end(chunk[, encoding][, callback])outgoingMessage.flushHeaders()outgoingMessage.getHeader(name)outgoingMessage.getHeaderNames()outgoingMessage.getHeaders()outgoingMessage.hasHeader(name)outgoingMessage.headersSentoutgoingMessage.pipe()outgoingMessage.removeHeader(name)outgoingMessage.setHeader(name, value)outgoingMessage.setHeaders(headers)outgoingMessage.setTimeout(msecs[, callback])outgoingMessage.socketoutgoingMessage.uncork()outgoingMessage.writableCorkedoutgoingMessage.writableEndedoutgoingMessage.writableFinishedoutgoingMessage.writableHighWaterMarkoutgoingMessage.writableLengthoutgoingMessage.writableObjectModeoutgoingMessage.write(chunk[, encoding][, callback])
- 事件:
http.METHODShttp.STATUS_CODEShttp.createServer([options][, requestListener])http.get(options[, callback])http.get(url[, options][, callback])http.globalAgenthttp.maxHeaderSizehttp.request(options[, callback])http.request(url[, options][, callback])http.validateHeaderName(name[, label])http.validateHeaderValue(name, value)http.setMaxIdleHTTPParsers(max)- 类:
WebSocket - 内置代理支持
- 类:
- 超文本传输协议
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- sqlite 轻型数据库
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
超文本传输协议#>
【HTTP】
源代码: lib/http.js
该模块包含客户端和服务器,可以通过 require('node:http')(CommonJS)或 import * as http from 'node:http'(ES 模块)导入。
【This module, containing both a client and server, can be imported via
require('node:http') (CommonJS) or import * as http from 'node:http' (ES module).】
Node.js 中的 HTTP 接口旨在支持该协议的许多传统上难以使用的特性。特别是大规模的、可能分块编码的消息。该接口小心设计,从不缓冲整个请求或响应,因此用户能够流式传输数据。
【The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.】
HTTP 消息头由类似如下的对象表示:
【HTTP message headers are represented by an object like this:】
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*/*" }
键会被转换为小写。值不会被修改。
【Keys are lowercased. Values are not modified.】
为了支持所有可能的 HTTP 应用,Node.js 的 HTTP API 属于非常底层的接口。它仅处理流操作和消息解析。它会将消息解析为头部和主体,但不会解析实际的头部内容或主体内容。
【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.】
有关重复标题的处理方式,请参见 message.headers。
【See message.headers for details on how duplicate headers are handled.】
rawHeaders 属性中保留了接收到的原始头信息,它是一个 [key, value, key2, value2, ...] 的数组。例如,之前的消息头对象可能有如下的 rawHeaders 列表:
【The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders
list like the following:】
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'example.com',
'accepT', '*/*' ]
类:http.Agent#>
【Class: http.Agent】
Agent 负责管理 HTTP 客户端的连接持久性和重用。它维护一个针对特定主机和端口的待处理请求队列,为每个请求队列复用单个套接字连接,直到队列为空,此时套接字要么被销毁,要么被放入池中,以便再次用于对相同主机和端口的请求。套接字是被销毁还是放入池中取决于 keepAlive 选项。
【An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.】
连接池中的连接已启用 TCP Keep-Alive,但服务器仍可能关闭空闲连接,在这种情况下,它们将被从连接池中移除,并且在对该主机和端口发起新的 HTTP 请求时会建立新的连接。服务器也可能拒绝在同一连接上处理多个请求,那么每个请求都必须重新建立连接,无法进行连接复用。Agent 仍然会向该服务器发起请求,但每个请求都将在新的连接上进行。
【Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.】
当连接被客户端或服务器关闭时,它将从连接池中移除。连接池中任何未使用的套接字都会被取消引用,以便在没有未完成请求时不会保持 Node.js 进程运行。(参见 socket.unref())。
【When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()).】
在不再使用 Agent 实例时释放它是一个好习惯,因为未使用的套接字会消耗操作系统资源。
【It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.】
当套接字触发 'close' 事件或 'agentRemove' 事件时,该套接字会从代理中移除。如果打算在不将 HTTP 请求保留在代理中的情况下长时间保持一个 HTTP 请求,可以像下面这样做:
【Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:】
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
代理也可以用于单独的请求。通过向 http.get() 或 http.request() 函数提供 {agent: false} 作为选项,将使用具有默认选项的一次性 Agent 来处理客户端连接。
【An agent may also be used for an individual request. By providing
{agent: false} as an option to the http.get() or http.request()
functions, a one-time use Agent with default options will be used
for the client connection.】
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
new Agent([options])#>
options<Object> 可在代理上设置的可配置选项集合。可以包含以下字段:keepAlive<boolean> 即使没有未完成的请求,也保持套接字存在,以便将来可以使用这些套接字而无需重新建立 TCP 连接。不要与Connection头的keep-alive值混淆。使用 agent 时,总是会发送Connection: keep-alive头,除非明确指定了Connection头,或者keepAlive和maxSockets选项分别设置为false和Infinity,在这种情况下将使用Connection: close。默认值:false.keepAliveMsecs<number> 使用keepAlive选项时,指定 TCP Keep-Alive 数据包的 初始延迟。当keepAlive选项为false或undefined时,此项将被忽略。默认值:1000。agentKeepAliveTimeoutBuffer在确定套接字过期时间时,从服务器提供的keep-alive: timeout=...提示中减去的 <number> 毫秒。这个缓冲时间有助于确保代理在服务器关闭套接字之前稍微关闭它,从而减少在即将被服务器关闭的套接字上发送请求的可能性。默认值:1000。maxSockets<number> 每个主机允许的最大套接字数。如果同一主机打开多个并发连接,每个请求将使用新的套接字,直到达到maxSockets值。如果主机尝试打开的连接数超过maxSockets,额外的请求将进入待处理请求队列,并在现有连接终止时进入活动连接状态。这确保了在任何时间点,从给定主机最多只有maxSockets个活动连接。默认值:Infinity。maxTotalSockets<number> 允许所有主机使用的最大套接字总数。每个请求将使用一个新的套接字,直到达到最大值。 默认值:Infinity。maxFreeSockets<number> 每个主机保持空闲状态的最大套接字数量。仅在keepAlive设置为true时有效。默认值:256。scheduling<string> 在选择下一个可用套接字时应用的调度策略。它可以是'fifo'或'lifo'。 这两种调度策略的主要区别在于'lifo'会选择最近使用的套接字,而'fifo'会选择最久未使用的套接字。 在请求速率较低的情况下,'lifo'调度可以降低选择已因不活动而被服务器关闭的套接字的风险。 在请求速率较高的情况下,'fifo'调度可以最大化打开的套接字数量,而'lifo'调度会尽可能保持套接字数量较少。 默认值:'lifo'。timeout<number> 套接字超时(毫秒)。这将设置套接字创建时的超时时间。proxyEnv<Object> | <undefined> 代理配置的环境变量。详情请参见 内置代理支持。默认值:undefinedHTTP_PROXY<string> | <undefined> HTTP 请求应使用的代理服务器 URL。如果未定义,则 HTTP 请求不使用代理。HTTPS_PROXY<string> | <undefined> 用于 HTTPS 请求应使用的代理服务器的 URL。如果未定义,则 HTTPS 请求不使用代理。NO_PROXY<string> | <undefined> 指定不应通过代理的端点的模式。http_proxy<string> | <undefined> 与HTTP_PROXY相同。如果两者都设置了,http_proxy优先。https_proxy<string> | <undefined> 与HTTPS_PROXY相同。如果两者都设置了,https_proxy优先。no_proxy<string> | <undefined> 与NO_PROXY相同。如果两者都设置了,no_proxy优先。
defaultPort<number> 当请求中未指定端口时使用的默认端口。默认值:80。protocol<string> 代理使用的协议。默认值:'http:'。
socket.connect() 中的 options 也受支持。
要配置其中的任何一个,必须创建一个自定义的 http.Agent 实例。
【To configure any of them, a custom http.Agent instance must be created.】
import { Agent, request } from 'node:http';
const keepAliveAgent = new Agent({ keepAlive: true });
options.agent = keepAliveAgent;
request(options, onResponseCallback);const http = require('node:http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
agent.createConnection(options[, callback])#>
options<Object> 包含连接详细信息的选项。检查net.createConnection()以了解选项的格式callback<Function> 接收已创建套接字的回调函数- 返回:<stream.Duplex>
生成用于 HTTP 请求的套接字/流。
【Produces a socket/stream to be used for HTTP requests.】
默认情况下,该函数与 net.createConnection() 相同。但是,如果需要更大的灵活性,自定义代理可以覆盖此方法。
【By default, this function is the same as net.createConnection(). However,
custom agents may override this method in case greater flexibility is desired.】
可以通过两种方式提供套接字/流:一种是从此函数返回套接字/流,另一种是将套接字/流传递给 callback。
【A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to callback.】
此方法保证返回一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了除 <net.Socket> 之外的套接字类型。
【This method is guaranteed to return an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
callback 的签名是 (err, stream)。
agent.keepSocketAlive(socket)#>
socket<stream.Duplex>
当 socket 从请求中分离并可能由 Agent 持久化时调用。默认行为是:
【Called when socket is detached from a request and could be persisted by the
Agent. Default behavior is to:】
socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;
此方法可以被某个特定的 Agent 子类重写。如果此方法返回一个假值,套接字将被销毁,而不是保留以供下一个请求使用。
【This method can be overridden by a particular Agent subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.】
socket 参数可以是 <net.Socket> 的一个实例,或者是 <stream.Duplex> 的一个子类。
【The socket argument can be an instance of <net.Socket>, a subclass of
<stream.Duplex>.】
agent.reuseSocket(socket, request)#>
socket<stream.Duplex>request<http.ClientRequest>
当 socket 因保活选项而被持久化后附加到 request 时调用。默认行为是:
【Called when socket is attached to request after being persisted because of
the keep-alive options. Default behavior is to:】
socket.ref();
此方法可以被特定的 Agent 子类重写。
【This method can be overridden by a particular Agent subclass.】
socket 参数可以是 <net.Socket> 的一个实例,或者是 <stream.Duplex> 的一个子类。
【The socket argument can be an instance of <net.Socket>, a subclass of
<stream.Duplex>.】
agent.destroy()#>
销毁代理当前正在使用的所有套接字。
【Destroy any sockets that are currently in use by the agent.】
通常不需要这样做。然而,如果使用启用了 keepAlive 的代理,那么在代理不再需要时最好明确关闭它。否则,套接字可能会在服务器终止它们之前保持打开状态相当长的时间。
【It is usually not necessary to do this. However, if using an
agent with keepAlive enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.】
agent.freeSockets#>
- 类型: <Object>
一个对象,其中包含当前由代理等待使用的套接字数组,当启用 keepAlive 时使用。请勿修改。
【An object which contains arrays of sockets currently awaiting use by
the agent when keepAlive is enabled. Do not modify.】
freeSockets 列表中的套接字将在 'timeout' 时被自动销毁并从数组中移除。
【Sockets in the freeSockets list will be automatically destroyed and
removed from the array on 'timeout'.】
agent.getName([options])#>
为一组请求选项获取一个唯一名称,以确定连接是否可以重用。对于 HTTP 代理,这会返回 host:port:localAddress 或 host:port:localAddress:family。对于 HTTPS 代理,名称包括 CA、证书、加密套件以及其他决定套接字可重用性的 HTTPS/TLS 特定选项。
【Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
host:port:localAddress or host:port:localAddress:family. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.】
agent.maxFreeSockets#>
- 类型:<number>
默认设置为 256。对于启用了 keepAlive 的代理,这将设置在空闲状态下保持开放的最大套接字数量。
【By default set to 256. For agents with keepAlive enabled, this
sets the maximum number of sockets that will be left open in the free
state.】
agent.maxSockets#>
- 类型:<number>
默认设置为 Infinity。决定代理每个源可以同时打开的套接字数量。源是 agent.getName() 返回的值。
【By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of agent.getName().】
agent.maxTotalSockets#>
- 类型:<number>
默认设置为 Infinity。确定代理可以同时打开的套接字数量。与 maxSockets 不同,该参数适用于所有来源。
【By default set to Infinity. Determines how many concurrent sockets the agent
can have open. Unlike maxSockets, this parameter applies across all origins.】
agent.requests#>
- 类型: <Object>
一个包含尚未分配到套接字的请求队列的对象。请勿修改。
【An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.】
agent.sockets#>
- 类型: <Object>
一个包含代理当前正在使用的套接字数组的对象。请勿修改。
【An object which contains arrays of sockets currently in use by the agent. Do not modify.】
类:http.ClientRequest#>
【Class: http.ClientRequest】
该对象在内部创建,并由 http.request() 返回。它表示一个正在进行中的请求,其头信息已经被排队。头信息仍然可以通过 setHeader(name, value)、getHeader(name)、removeHeader(name) API 进行修改。实际的头信息将在发送第一块数据时或调用 request.end() 时一起发送。
【This object is created internally and returned from http.request(). It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value),
getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when calling request.end().】
要获取响应,请在请求对象上为 'response' 添加一个监听器。当响应头被接收时,'response' 将从请求对象发出。'response' 事件会使用一个参数执行,该参数是 http.IncomingMessage 的一个实例。
【To get the response, add a listener for 'response' to the request object.
'response' will be emitted from the request object when the response
headers have been received. The 'response' event is executed with one
argument which is an instance of http.IncomingMessage.】
在 'response' 事件期间,可以向 response 对象添加监听器;特别是监听 'data' 事件。
【During the 'response' event, one can add listeners to the
response object; particularly to listen for the 'data' event.】
如果没有添加 'response' 处理程序,那么响应将被完全丢弃。然而,如果添加了 'response' 事件处理程序,则必须使用响应对象中的数据,可以通过在每次出现 'readable' 事件时调用 response.read(),或者添加 'data' 处理程序,或者调用 .resume() 方法来消费数据。在数据被消费之前,'end' 事件不会触发。此外,在数据被读取之前,它会占用内存,这最终可能导致“进程内存不足”错误。
【If no 'response' handler is added, then the response will be
entirely discarded. However, if a 'response' event handler is added,
then the data from the response object must be consumed, either by
calling response.read() whenever there is a 'readable' event, or
by adding a 'data' handler, or by calling the .resume() method.
Until the data is consumed, the 'end' event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.】
为了向后兼容,res 只有在注册了 'error' 监听器时才会发出 'error'。
【For backward compatibility, res will only emit 'error' if there is an
'error' listener registered.】
设置 Content-Length 头以限制响应主体的大小。如果 response.strictContentLength 设置为 true,Content-Length 头的值不匹配将导致抛出一个 Error,其由 code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH' 标识。
【Set Content-Length header to limit the response body size.
If response.strictContentLength is set to true, mismatching the
Content-Length header value will result in an Error being thrown,
identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.】
Content-Length 的值应以字节为单位,而不是字符。使用 Buffer.byteLength() 来确定正文的字节长度。
事件:'abort'#>
【Event: 'abort'】
'close' 事件。当请求被客户端中止时触发。这个事件仅在第一次调用 abort() 时触发。
【Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().】
事件:'close'#>
【Event: 'close'】
表示请求已完成,或其底层连接被提前终止(在响应完成之前)。
【Indicates that the request is completed, or its underlying connection was terminated prematurely (before the response completion).】
事件:'connect'#>
【Event: 'connect'】
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
每当服务器回应带有 CONNECT 方法的请求时都会触发此事件。如果没有监听此事件,接收到 CONNECT 方法的客户端连接将被关闭。
【Emitted each time a server responds to a request with a CONNECT method. If
this event is not being listened for, clients receiving a CONNECT method will
have their connections closed.】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
一个客户端和服务器示例,演示如何监听 'connect' 事件:
【A client and server pair demonstrating how to listen for the 'connect' event:】
import { createServer, request } from 'node:http';
import { connect } from 'node:net';
import { URL } from 'node:url';
// Create an HTTP tunneling proxy
const proxy = createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`);
const serverSocket = connect(port || 80, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
});
// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80',
};
const req = request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// Make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});const http = require('node:http');
const net = require('node:net');
const { URL } = require('node:url');
// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`);
const serverSocket = net.connect(port || 80, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
});
// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80',
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// Make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});
事件:'continue'#>
【Event: 'continue'】
当服务器发送 '100 Continue' HTTP 响应时触发,通常是因为请求包含 'Expect: 100-continue'。这是指示客户端应发送请求体的指令。
【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.】
事件:'finish'#>
【Event: 'finish'】
当请求已发送时会触发该事件。更具体地说,当响应头和响应体的最后一段已交给操作系统通过网络传输时,会触发此事件。这并不意味着服务器已经收到任何内容。
【Emitted when the request has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the server has received anything yet.】
事件:'information'#>
【Event: 'information'】
info<Object>
当服务器发送 1xx 中间响应(不包括 101 Upgrade)时触发。此事件的监听器将接收到一个对象,该对象包含 HTTP 版本、状态码、状态信息、键值对形式的头部对象,以及一个数组,数组中依次包含原始头部名称及其对应的值。
【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.】
import { request } from 'node:http';
const options = {
host: '127.0.0.1',
port: 8080,
path: '/length_request',
};
// Make a request
const req = request(options);
req.end();
req.on('information', (info) => {
console.log(`Got information prior to main response: ${info.statusCode}`);
});const http = require('node:http');
const options = {
host: '127.0.0.1',
port: 8080,
path: '/length_request',
};
// Make a request
const req = http.request(options);
req.end();
req.on('information', (info) => {
console.log(`Got information prior to main response: ${info.statusCode}`);
});
由于 101 升级状态打破了传统的 HTTP 请求/响应链,例如 WebSocket、就地 TLS 升级或 HTTP 2.0,因此不会触发此事件。要接收 101 升级通知,请改为监听 'upgrade' 事件。
事件:'response'#>
【Event: 'response'】
response<http.IncomingMessage>
当收到对此请求的响应时触发。此事件仅触发一次。
【Emitted when a response is received to this request. This event is emitted only once.】
事件:'socket'#>
【Event: 'socket'】
socket<stream.Duplex>
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
事件:'timeout'#>
【Event: 'timeout'】
当底层套接字因长时间未活动而超时时发出。 这仅通知套接字处于空闲状态。请求必须手动销毁。
【Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be destroyed manually.】
另请参见:request.setTimeout()。
【See also: request.setTimeout().】
事件:'upgrade'#>
【Event: 'upgrade'】
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
每当服务器响应带有升级请求时都会触发此事件。如果未监听此事件且响应状态码为101 Switching Protocols,接收到升级头的客户端将会关闭连接。
【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.】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
一个客户端-服务器示例,演示如何监听 'upgrade' 事件。
【A client server pair demonstrating how to listen for the 'upgrade' event.】
import http from 'node:http';
import process from 'node:process';
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
server.on('upgrade', (req, socket, head) => {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// Now that server is running
server.listen(1337, '127.0.0.1', () => {
// make a request
const options = {
port: 1337,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket',
},
};
const req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});const http = require('node:http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
server.on('upgrade', (req, socket, head) => {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// Now that server is running
server.listen(1337, '127.0.0.1', () => {
// make a request
const options = {
port: 1337,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket',
},
};
const req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});
request.abort()#>
request.destroy()。将请求标记为中止。调用此操作将导致响应中剩余的数据被丢弃,并且套接字将被销毁。
【Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.】
request.aborted#>
request.destroyed。- 类型:<boolean>
request.aborted 属性将在请求被中止时为 true。
【The request.aborted property will be true if the request has
been aborted.】
request.connection#>
request.socket。【See request.socket.】
request.cork()#>
【See writable.cork().】
request.end([data[, encoding]][, callback])#>
data<string> | <Buffer> | <Uint8Array>encoding<string>callback<Function>- 返回:<this>
完成发送请求。如果有任何部分的请求体未发送,它会将其刷新到流中。如果请求是分块的,这将发送终止的 `'0
'`。
【Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n'.】
如果指定了 data,等同于先调用 request.write(data, encoding),然后再调用 request.end(callback)。
【If data is specified, it is equivalent to calling
request.write(data, encoding) followed by request.end(callback).】
如果指定了 callback,当请求流完成时,它将被调用。
【If callback is specified, it will be called when the request stream
is finished.】
request.destroy([error])#>
销毁请求。可以选择发送一个 'error' 事件,并发送一个 'close' 事件。调用此方法会导致响应中剩余的数据被丢弃,并销毁套接字。
【Destroy the request. Optionally emit an 'error' event,
and emit a 'close' event. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.】
有关详细信息,请参见writable.destroy()。
【See writable.destroy() for further details.】
request.destroyed#>
- 类型:<boolean>
在调用 request.destroy() 之后为 true。
【Is true after request.destroy() has been called.】
有关详细信息,请参见writable.destroyed。
【See writable.destroyed for further details.】
request.finished#>
request.writableEnded。- 类型:<boolean>
request.finished 属性在调用 request.end() 后将为 true。如果请求是通过 http.get() 发起的,request.end() 将会自动被调用。
【The request.finished property will be true if request.end()
has been called. request.end() will automatically be called if the
request was initiated via http.get().】
request.flushHeaders()#>
刷新请求头。
【Flushes the request headers.】
出于效率原因,Node.js 通常会缓冲请求头,直到调用 request.end() 或写入请求数据的第一块时。然后它会尝试将请求头和数据打包到一个 TCP 数据包中。
【For efficiency reasons, Node.js normally buffers the request headers until
request.end() is called or the first chunk of request data is written. It
then tries to pack the request headers and data into a single TCP packet.】
这通常是理想的(它可以节省一次 TCP 往返),但当第一次数据可能很晚才发送时就不适用了。request.flushHeaders() 可以绕过这种优化并启动请求。
【That's usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. request.flushHeaders() bypasses
the optimization and kickstarts the request.】
request.getHeader(name)#>
读取请求中的一个头部。名称不区分大小写。返回值的类型取决于提供给 request.setHeader() 的参数。
【Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
request.setHeader().】
request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]
request.getHeaderNames()#>
- 返回值: <string[]>
返回一个数组,包含当前要发送的唯一头部名称。所有头部名称均为小写。
【Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.】
request.setHeader('Foo', 'bar');
request.setHeader('Cookie', ['foo=bar', 'bar=baz']);
const headerNames = request.getHeaderNames();
// headerNames === ['foo', 'cookie']
request.getHeaders()#>
- 返回:<Object>
返回当前发送的头信息的浅拷贝。由于使用了浅拷贝,数组值可以在不额外调用各种与头信息相关的 http 模块方法的情况下被修改。返回对象的键是头信息的名称,值是相应的头信息值。所有头信息名称都是小写。
【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.】
request.getHeaders() 方法返回的对象 不会 从 JavaScript 的 Object 原型继承。这意味着常用的 Object 方法,例如 obj.toString()、obj.hasOwnProperty() 等未定义,将无法使用。
【The object returned by the request.getHeaders() method does not
prototypically inherit from the JavaScript Object. This means that typical
Object methods such as obj.toString(), obj.hasOwnProperty(), and others
are not defined and will not work.】
request.setHeader('Foo', 'bar');
request.setHeader('Cookie', ['foo=bar', 'bar=baz']);
const headers = request.getHeaders();
// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }
request.getRawHeaderNames()#>
- 返回值: <string[]>
返回一个包含当前输出原始头的唯一名称的数组。头名称以其原始大小写返回。
【Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.】
request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = request.getRawHeaderNames();
// headerNames === ['Foo', 'Set-Cookie']
request.hasHeader(name)#>
如果由 name 指定的头目前已设置在发出的头中,则返回 true。头名称匹配不区分大小写。
【Returns true if the header identified by name is currently set in the
outgoing headers. The header name matching is case-insensitive.】
const hasContentType = request.hasHeader('content-type');
request.maxHeadersCount#>
- 类型: <number> 默认值:
2000
限制最大响应头数量。如果设置为0,则不限制。
【Limits maximum response headers count. If set to 0, no limit will be applied.】
request.path#>
- 类型:<string> 请求路径。
request.method#>
- 类型:<string> 请求方法。
request.host#>
- 类型:<string> 请求主机。
request.protocol#>
- 类型:<string> 请求协议。
request.removeHeader(name)#>
name<string>
删除已定义到标头对象中的标头。
【Removes a header that's already defined into headers object.】
request.removeHeader('Content-Type');
request.reusedSocket#>
- 类型:<boolean> 请求是否通过重用的套接字发送。
通过启用长连接的代理发送请求时,底层套接字可能会被重用。但如果服务器在不合适的时间关闭连接,客户端可能会遇到 'ECONNRESET' 错误。
【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.】
import http from 'node:http';
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeoutconst http = require('node:http');
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
通过标记一个请求是否重用了套接字,我们可以基于此进行自动错误重试。
【By marking a request whether it reused socket or not, we can do automatic error retry base on it.】
import http from 'node:http';
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();const http = require('node:http');
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
request.setHeader(name, value)#>
为 headers 对象设置单个头部值。如果该头部已存在于即将发送的头部中,其值将被替换。此处使用字符串数组可以发送具有相同名称的多个头部。非字符串值将按原样存储。因此,request.getHeader() 可能会返回非字符串值。然而,非字符串值在网络传输时将被转换为字符串。
【Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, request.getHeader() may return
non-string values. However, the non-string values will be converted to strings
for network transmission.】
request.setHeader('Content-Type', 'application/json');
或者
【or】
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
当值是字符串时,如果它包含 latin1 编码之外的字符,将会抛出异常。
【When the value is a string an exception will be thrown if it contains
characters outside the latin1 encoding.】
如果你需要在值中传递 UTF-8 字符,请使用 RFC 8187 标准对该值进行编码。
【If you need to pass UTF-8 characters in the value please encode the value using the RFC 8187 standard.】
const filename = 'Rock 🎵.txt';
request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`);
request.setNoDelay([noDelay])#>
noDelay<boolean>
一旦套接字被分配给此请求并且已连接,socket.setNoDelay() 将被调用。
【Once a socket is assigned to this request and is connected
socket.setNoDelay() will be called.】
request.setSocketKeepAlive([enable][, initialDelay])#>
一旦套接字被分配给此请求并且已连接,socket.setKeepAlive() 将被调用。
【Once a socket is assigned to this request and is connected
socket.setKeepAlive() will be called.】
request.setTimeout(timeout[, callback])#>
timeout在请求超时前的毫秒数 <number>。callback<Function> 可选函数,在超时发生时调用。与绑定到'timeout'事件相同。- 返回: <http.ClientRequest>
一旦套接字被分配给此请求并且已连接,socket.setTimeout() 将被调用。
【Once a socket is assigned to this request and is connected
socket.setTimeout() will be called.】
request.socket#>
引用底层套接字。通常用户不需要访问此属性。特别是,由于协议解析器如何附加到套接字,套接字不会触发 'readable' 事件。
【Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit 'readable' events
because of how the protocol parser attaches to the socket.】
import http from 'node:http';
const options = {
host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// Consume response object
});const http = require('node:http');
const options = {
host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// Consume response object
});
此属性保证是 <net.Socket> 类的一个实例,<stream.Duplex> 的子类,除非用户指定了 <net.Socket> 以外的套接字类型。
【This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket>.】
request.uncork()#>
【See writable.uncork().】
request.writableEnded#>
- 类型:<boolean>
true 表示 request.end() 已被调用。此属性不表示数据是否已被刷新,如需此功能,请使用 request.writableFinished。
【Is true after request.end() has been called. This property
does not indicate whether the data has been flushed, for this use
request.writableFinished instead.】
request.writableFinished#>
- 类型:<boolean>
如果所有数据在 'finish' 事件发出之前立即被刷新到底层系统,则为 true。
【Is true if all data has been flushed to the underlying system, immediately
before the 'finish' event is emitted.】
request.write(chunk[, encoding][, callback])#>
chunk<string> | <Buffer> | <Uint8Array>encoding<string>callback<Function>- 返回:<boolean>
发送一段请求体。此方法可以被多次调用。如果没有设置 Content-Length,数据将会自动使用 HTTP 分块传输编码,这样服务器就知道数据何时结束。会添加 Transfer-Encoding: chunked 头。调用 request.end() 是完成请求发送所必需的。
【Sends a chunk of the body. This method can be called multiple times. If no
Content-Length is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
Transfer-Encoding: chunked header is added. Calling request.end()
is necessary to finish sending the request.】
encoding 参数是可选的,仅在 chunk 是字符串时适用。默认值为 'utf8'。
【The encoding argument is optional and only applies when chunk is a string.
Defaults to 'utf8'.】
callback 参数是可选的,当这段数据被刷新时将被调用,但仅在数据块非空时才会调用。
【The callback argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.】
如果所有数据都成功刷新到内核缓冲区,则返回 true。如果所有或部分数据被排队在用户内存中,则返回 false。当缓冲区再次空闲时,会触发 'drain' 事件。
【Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in user memory.
'drain' will be emitted when the buffer is free again.】
当 write 函数被调用时,如果传入空字符串或缓冲区,它不会做任何操作,并会等待更多输入。
【When write function is called with empty string or buffer, it does
nothing and waits for more input.】
类:http.Server#>
【Class: http.Server】
- 扩展自: <net.Server>
事件:'checkContinue'#>
【Event: 'checkContinue'】
request<http.IncomingMessage>response<http.ServerResponse>
每次收到带有 HTTP Expect: 100-continue 的请求时都会触发此事件。如果没有监听此事件,服务器将会自动适当地响应 100 Continue。
【Emitted each time a request with an HTTP Expect: 100-continue is received.
If this event is not listened for, the server will automatically respond
with a 100 Continue as appropriate.】
处理此事件涉及在客户端应继续发送请求体时调用 response.writeContinue(),或者在客户端不应继续发送请求体时生成适当的 HTTP 响应(例如 400 Bad Request)。
【Handling this event involves calling response.writeContinue() if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.】
当此事件被触发并处理时,'request' 事件将不会被触发。
【When this event is emitted and handled, the 'request' event will
not be emitted.】
事件:'checkExpectation'#>
【Event: 'checkExpectation'】
request<http.IncomingMessage>response<http.ServerResponse>
每当收到带有 HTTP Expect 头且其值不是 100-continue 的请求时都会触发此事件。如果没有监听此事件,服务器将自动使用适当的 417 Expectation Failed 响应。
【Emitted each time a request with an HTTP Expect header is received, where the
value is not 100-continue. If this event is not listened for, the server will
automatically respond with a 417 Expectation Failed as appropriate.】
当此事件被触发并处理时,'request' 事件将不会被触发。
【When this event is emitted and handled, the 'request' event will
not be emitted.】
事件:'clientError'#>
【Event: 'clientError'】
exception<Error>socket<stream.Duplex>
如果客户端连接触发 'error' 事件,它将被转发到这里。该事件的监听器负责关闭或销毁底层套接字。例如,可以希望通过自定义的 HTTP 响应更优雅地关闭套接字,而不是突然断开连接。套接字必须在监听器结束之前关闭或销毁。
【If a client connection emits an 'error' event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection. The socket
must be closed or destroyed before the listener ends.】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
默认行为是尝试使用 HTTP '400 Bad Request' 关闭套接字,或者在发生 HPE_HEADER_OVERFLOW 错误的情况下使用 HTTP '431 Request Header Fields Too Large'。如果套接字不可写或当前附加的 http.ServerResponse 的头信息已发送,它会被立即销毁。
【Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
HPE_HEADER_OVERFLOW error. If the socket is not writable or headers
of the current attached http.ServerResponse has been sent, it is
immediately destroyed.】
socket 是错误来源的 net.Socket 对象。
import http from 'node:http';
const server = http.createServer((req, res) => {
res.end();
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);const http = require('node:http');
const server = http.createServer((req, res) => {
res.end();
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
当 'clientError' 事件发生时,不会有 request 或 response 对象,因此任何发送的 HTTP 响应,包括响应头和负载,必须直接写入 socket 对象。必须注意确保响应是格式正确的 HTTP 响应消息。
【When the 'clientError' event occurs, there is no request or response
object, so any HTTP response sent, including response headers and payload,
must be written directly to the socket object. Care must be taken to
ensure the response is a properly formatted HTTP response message.】
err 是一个 Error 实例,并带有两个额外的列:
bytesParsed:Node.js 可能已正确解析的请求数据包的字节数;rawPacket:当前请求的原始数据包。
在某些情况下,客户端已经收到了响应和/或套接字已经被销毁,例如发生 ECONNRESET 错误时。在尝试向套接字发送数据之前,最好先检查它是否仍然可写。
【In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of ECONNRESET errors. Before
trying to send data to the socket, it is better to check that it is still
writable.】
server.on('clientError', (err, socket) => {
if (err.code === 'ECONNRESET' || !socket.writable) {
return;
}
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
事件:'close'#>
【Event: 'close'】
服务器关闭时触发。
【Emitted when the server closes.】
事件:'connect'#>
【Event: 'connect'】
request<http.IncomingMessage> HTTP 请求的参数,就像在'request'事件中一样socket<stream.Duplex> 服务器和客户端之间的网络套接字head<Buffer> 隧道流的第一个数据包(可能为空)
每当客户端请求 HTTP CONNECT 方法时都会触发此事件。如果没有监听此事件,请求 CONNECT 方法的客户端其连接将被关闭。
【Emitted each time a client requests an HTTP CONNECT method. If this event is
not listened for, then clients requesting a CONNECT method will have their
connections closed.】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
在此事件被触发后,请求的套接字将不会有 'data' 事件监听器,这意味着需要绑定监听器才能处理发送到该套接字的服务器数据。
【After this event is emitted, the request's socket will not have a 'data'
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.】
事件:'connection'#>
【Event: 'connection'】
socket<stream.Duplex>
当建立新的 TCP 流时,会触发此事件。socket 通常是 net.Socket 类型的对象。通常用户不需要访问此事件。特别是,由于协议解析器附加到套接字的方式,套接字不会触发 'readable' 事件。socket 也可以通过 request.socket 访问。
【This event is emitted when a new TCP stream is established. socket is
typically an object of type net.Socket. Usually users will not want to
access this event. In particular, the socket will not emit 'readable' events
because of how the protocol parser attaches to the socket. The socket can
also be accessed at request.socket.】
此事件也可以由用户显式触发,以向 HTTP 服务器注入连接。在这种情况下,可以传递任何 Duplex 流。
【This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any Duplex stream can be passed.】
如果在这里调用 socket.setTimeout(),当套接字处理完请求后,超时时间将被替换为 server.keepAliveTimeout(如果 server.keepAliveTimeout 非零)。
【If socket.setTimeout() is called here, the timeout will be replaced with
server.keepAliveTimeout when the socket has served a request (if
server.keepAliveTimeout is non-zero).】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
事件:'dropRequest'#>
【Event: 'dropRequest'】
request<http.IncomingMessage> HTTP 请求的参数,就像在'request'事件中一样socket<stream.Duplex> 服务器和客户端之间的网络套接字
当套接字上的请求数量达到 server.maxRequestsPerSocket 阈值时,服务器将丢弃新的请求并触发 'dropRequest' 事件,然后向客户端发送 503。
【When the number of requests on a socket reaches the threshold of
server.maxRequestsPerSocket, the server will drop new requests
and emit 'dropRequest' event instead, then send 503 to client.】
事件:'request'#>
【Event: 'request'】
request<http.IncomingMessage>response<http.ServerResponse>
每次有请求时都会发出。每个连接可能有多个请求(在 HTTP Keep-Alive 连接的情况下)。
【Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).】
事件:'upgrade'#>
【Event: 'upgrade'】
request<http.IncomingMessage> HTTP 请求的参数,就像在'request'事件中一样socket<stream.Duplex> 服务器和客户端之间的网络套接字head<Buffer> 升级后的流的第一个数据包(可能为空)
每当客户端的 HTTP 升级请求被接受时就会触发。默认情况下,所有 HTTP 升级请求都会被忽略(即只会触发常规的 'request' 事件,遵循正常的 HTTP 请求/响应流程),除非你监听此事件,在这种情况下它们都会被接受(即会触发 'upgrade' 事件,并且未来的通信必须直接通过原始套接字处理)。你可以通过使用服务器的 shouldUpgradeCallback 选项来更精确地控制这一点。
【Emitted each time a client's HTTP upgrade request is accepted. By default
all HTTP upgrade requests are ignored (i.e. only regular 'request' events
are emitted, sticking with the normal HTTP request/response flow) unless you
listen to this event, in which case they are all accepted (i.e. the 'upgrade'
event is emitted instead, and future communication must handled directly
through the raw socket). You can control this more precisely by using the
server shouldUpgradeCallback option.】
参加此活动是可选的,客户不能要求更改协议。
【Listening to this event is optional and clients cannot insist on a protocol change.】
在此事件被触发后,请求的套接字将不会有 'data' 事件监听器,这意味着需要绑定监听器才能处理发送到该套接字的服务器数据。
【After this event is emitted, the request's socket will not have a 'data'
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.】
如果 shouldUpgradeCallback 接受了升级,但没有注册事件处理程序,则套接字将被销毁,从而导致客户端的连接立即关闭。
【If an upgrade is accepted by shouldUpgradeCallback but no event handler
is registered then the socket is destroyed, resulting in an immediate
connection closure for the client.】
此事件保证会传递一个 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类,除非用户指定了其他类型的套接字而不是 <net.Socket>。
【This event is guaranteed to be passed an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specifies a socket type other than <net.Socket>.】
server.close([callback])#>
callback<Function>
阻止服务器接受新的连接,并关闭所有未发送请求或未等待响应的与该服务器连接的连接。详见 net.Server.close()。
【Stops the server from accepting new connections and closes all connections
connected to this server which are not sending a request or waiting for
a response.
See net.Server.close().】
const http = require('node:http');
const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
// Close the server after 10 seconds
setTimeout(() => {
server.close(() => {
console.log('server on port 8000 closed successfully');
});
}, 10000);
server.closeAllConnections()#>
关闭与此服务器连接的所有已建立的 HTTP(S) 连接,包括正在发送请求或等待响应的活动连接。这不会销毁已升级到其他协议的套接字,例如 WebSocket 或 HTTP/2。
【Closes all established HTTP(S) connections connected to this server, including active connections connected to this server which are sending a request or waiting for a response. This does not destroy sockets upgraded to a different protocol, such as WebSocket or HTTP/2.】
这是强制关闭所有连接的方式,应谨慎使用。每当与
server.close一起使用时,建议在调用server.close之后再调用此方法,以避免在调用此方法和调用server.close之间产生新的连接所引起的竞争条件。
const http = require('node:http');
const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
// Close the server after 10 seconds
setTimeout(() => {
server.close(() => {
console.log('server on port 8000 closed successfully');
});
// Closes all connections, ensuring the server closes successfully
server.closeAllConnections();
}, 10000);
server.closeIdleConnections()#>
关闭所有连接到此服务器但未发送请求或未等待响应的连接。
【Closes all connections connected to this server which are not sending a request or waiting for a response.】
从 Node.js 19.0.0 开始,不再需要在调用
server.close时同时调用此方法来回收keep-alive连接。使用它不会造成任何问题,而且对于需要支持 19.0.0 之前版本的库和应用来说,它有助于确保向后兼容性。每当将其与server.close一起使用时,建议在server.close之后调用此方法,以避免在调用此方法和server.close之间新连接被创建而产生的竞争条件。
const http = require('node:http');
const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
// Close the server after 10 seconds
setTimeout(() => {
server.close(() => {
console.log('server on port 8000 closed successfully');
});
// Closes idle connections, such as keep-alive connections. Server will close
// once remaining active connections are terminated
server.closeIdleConnections();
}, 10000);
server.headersTimeout#>
- 类型:<number> 默认值:
server.requestTimeout与60000中的最小值。
限制解析器等待接收完整 HTTP 头的时间。
【Limit the amount of time the parser will wait to receive the complete HTTP headers.】
如果超时到期,服务器会以状态码 408 响应,而不会将请求转发给请求监听器,然后关闭连接。
【If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.】
它必须设置为非零值(例如 120 秒),以防止在服务器未部署反向代理的情况下可能发生的拒绝服务攻击。
【It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.】
server.listen()#>
启动 HTTP 服务器以监听连接。此方法与 net.Server 的 server.listen() 相同。
【Starts the HTTP server listening for connections.
This method is identical to server.listen() from net.Server.】
server.listening#>
- 类型:<boolean> 表示服务器是否正在监听连接。
server.maxHeadersCount#>
- 类型: <number> 默认值:
2000
限制最大传入头数量。如果设置为0,将不应用任何限制。
【Limits maximum incoming headers count. If set to 0, no limit will be applied.】
server.requestTimeout#>
- 类型: <number> 默认:
300000
设置接收来自客户端的整个请求的超时时间(以毫秒为单位)。
【Sets the timeout value in milliseconds for receiving the entire request from the client.】
如果超时到期,服务器会以状态码 408 响应,而不会将请求转发给请求监听器,然后关闭连接。
【If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.】
它必须设置为非零值(例如 120 秒),以防止在服务器未部署反向代理的情况下可能发生的拒绝服务攻击。
【It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.】
server.setTimeout([msecs][, callback])#>
msecs<number> 默认值: 0(无限超时)callback<Function>- 返回值:<http.Server>
为套接字设置超时时间,如果发生超时,会在 Server 对象上触发 'timeout' 事件,并将套接字作为参数传递。
【Sets the timeout value for sockets, and emits a 'timeout' event on
the Server object, passing the socket as an argument, if a timeout
occurs.】
如果 Server 对象上存在 'timeout' 事件监听器,那么它将使用超时的套接字作为参数被调用。
【If there is a 'timeout' event listener on the Server object, then it
will be called with the timed-out socket as an argument.】
默认情况下,服务器不会对套接字进行超时处理。但是,如果为服务器的 'timeout' 事件分配了回调,则必须显式处理超时。
【By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's 'timeout' event, timeouts must be handled
explicitly.】
server.maxRequestsPerSocket#>
- 类型:<number> 每个套接字的请求数。默认: 0(无限制)
在关闭保持活动连接之前,套接字可以处理的最大请求数。
【The maximum number of requests socket can handle before closing keep alive connection.】
0 的值将禁用此限制。
【A value of 0 will disable the limit.】
当达到限制时,它会将 Connection 头的值设置为 close,但实际上不会关闭连接,在达到限制后发送的后续请求将会得到 503 Service Unavailable 作为响应。
【When the limit is reached it will set the Connection header value to close,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get 503 Service Unavailable as a response.】
server.timeout#>
- 类型:<number> 超时时间(毫秒)。**默认值:**0(无限超时)
在假定套接字已超时之前的非活动毫秒数。
【The number of milliseconds of inactivity before a socket is presumed to have timed out.】
值为 0 将会禁止对传入连接的超时处理。
【A value of 0 will disable the timeout behavior on incoming connections.】
套接字超时逻辑在连接时设置,因此更改此值只会影响与服务器的新连接,而不会影响任何现有连接。
【The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.】
server.keepAliveTimeout#>
- 类型:<number> 超时(毫秒)。默认值:
5000(5 秒)。
服务器在完成最后一次响应的写入后,需要等待额外传入数据的空闲毫秒数,然后套接字将被销毁。
【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.】
此超时值与server.keepAliveTimeoutBuffer选项结合使用以确定实际的套接字超时,计算公式为:
socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer
如果服务器在保持活动超时触发之前接收到新数据,它将重置常规的不活动超时,即server.timeout。
【This timeout value is combined with the
server.keepAliveTimeoutBuffer option to determine the actual socket
timeout, calculated as:
socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer
If the server receives new data before the keep-alive timeout has fired, it
will reset the regular inactivity timeout, i.e., server.timeout.】
将值设置为 0 会禁用对传入连接的 keep-alive 超时行为。
将值设置为 0 会使 HTTP 服务器的行为类似于 8.0.0 之前的 Node.js 版本,这些版本没有 keep-alive 超时。
【A value of 0 will disable the keep-alive timeout behavior on incoming
connections.
A value of 0 makes the HTTP server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.】
套接字超时逻辑是在连接时设置的,因此更改此值只会影响与服务器的新连接,而不会影响任何现有连接。
【The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.】
server.keepAliveTimeoutBuffer#>
- 类型:<number> 超时(毫秒)。默认值:
1000(1 秒)。
在 server.keepAliveTimeout 上增加了一个额外的缓冲时间,以延长内部套接字超时。
【An additional buffer time added to the
server.keepAliveTimeout to extend the internal socket timeout.】
此缓冲区通过将套接字超时稍微延长到广告的保持活动超时之外,帮助减少连接重置(ECONNRESET)错误。
【This buffer helps reduce connection reset (ECONNRESET) errors by increasing
the socket timeout slightly beyond the advertised keep-alive timeout.】
此选项仅适用于新传入的连接。
【This option applies only to new incoming connections.】
server[Symbol.asyncDispose]()#>
调用 server.close() 并返回一个在服务器关闭时完成的 Promise。
【Calls server.close() and returns a promise that fulfills when the
server has closed.】
类:http.ServerResponse#>
【Class: http.ServerResponse】
该对象由 HTTP 服务器内部创建,而不是由用户创建。它作为第二个参数传递给 'request' 事件。
【This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request' event.】
事件:'close'#>
【Event: 'close'】
表示响应已完成,或其底层连接被提前终止(在响应完成之前)。
【Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion).】
事件:'finish'#>
【Event: 'finish'】
当响应已发送时触发。更具体地说,当响应头和响应体的最后一部分已交给操作系统以通过网络传输时,将触发此事件。这并不意味着客户端已经收到任何内容。
【Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.】
response.addTrailers(headers)#>
headers<Object>
该方法向响应添加 HTTP 尾部头(即消息末尾的头)。
【This method adds HTTP trailing headers (a header but at the end of the message) to the response.】
只有在响应使用分块编码时才会发送尾部;如果没有使用(例如请求是 HTTP/1.0),它们将被静默丢弃。
【Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.】
HTTP 要求发送 Trailer 头以便发送尾部信息,其值中应包含头字段的列表。例如:
【HTTP requires the Trailer header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,】
response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
response.connection#>
response.socket。【See response.socket.】
response.cork()#>
【See writable.cork().】
response.end([data[, encoding]][, callback])#>
data<string> | <Buffer> | <Uint8Array>encoding<string>callback<Function>- 返回:<this>
此方法向服务器表示所有响应头和响应体都已发送;服务器应视此消息为已完成。每个响应都必须调用 response.end() 方法。
【This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, response.end(), MUST be called on each response.】
如果指定了 data,其效果类似于先调用 response.write(data, encoding),然后再调用 response.end(callback)。
【If data is specified, it is similar in effect to calling
response.write(data, encoding) followed by response.end(callback).】
如果指定了 callback,当响应流完成时,它将被调用。
【If callback is specified, it will be called when the response stream
is finished.】
response.finished#>
response.writableEnded。- 类型:<boolean>
response.finished 属性在调用了 response.end() 后将为 true。
【The response.finished property will be true if response.end()
has been called.】
response.flushHeaders()#>
刷新响应头。另请参见:request.flushHeaders()。
【Flushes the response headers. See also: request.flushHeaders().】
response.getHeader(name)#>
name<string>- 返回:数字 | 字符串 | 字符串[] | 未定义
读取已经排队但尚未发送给客户端的头部。名称不区分大小写。返回值的类型取决于提供给 response.setHeader() 的参数。
【Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to response.setHeader().】
response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
response.getHeaderNames()#>
- 返回值: <string[]>
返回一个数组,包含当前要发送的唯一头部名称。所有头部名称均为小写。
【Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.】
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
response.getHeaders()#>
- 返回:<Object>
返回当前发送的头信息的浅拷贝。由于使用了浅拷贝,数组值可以在不额外调用各种与头信息相关的 http 模块方法的情况下被修改。返回对象的键是头信息的名称,值是相应的头信息值。所有头信息名称都是小写。
【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.】
response.getHeaders() 方法返回的对象 不会 原型继承自 JavaScript Object。这意味着常用的 Object 方法,例如 obj.toString()、obj.hasOwnProperty() 等未定义,将无法使用。
【The object returned by the response.getHeaders() method does not
prototypically inherit from the JavaScript Object. This means that typical
Object methods such as obj.toString(), obj.hasOwnProperty(), and others
are not defined and will not work.】
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
response.hasHeader(name)#>
如果由 name 指定的头目前已设置在发出的头中,则返回 true。头名称匹配不区分大小写。
【Returns true if the header identified by name is currently set in the
outgoing headers. The header name matching is case-insensitive.】
const hasContentType = response.hasHeader('content-type');
response.headersSent#>
- 类型:<boolean>
布尔值(只读)。如果已发送头部则为真,否则为假。
【Boolean (read-only). True if headers were sent, false otherwise.】
response.removeHeader(name)#>
name<string>
删除排队等待隐式发送的标头。
【Removes a header that's queued for implicit sending.】
response.removeHeader('Content-Encoding');
response.req#>
对原始 HTTP request 对象的引用。
【A reference to the original HTTP request object.】
response.sendDate#>
- 类型:<boolean>
当值为 true 时,如果响应头中尚不存在 Date 头部,将会自动生成并发送该头部。默认值为 true。
【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.】
这只应在测试时禁用;HTTP 在响应中需要 Date 头。
【This should only be disabled for testing; HTTP requires the Date header in responses.】
response.setHeader(name, value)#>
name<string>value数字 | 字符串 | 字符串数组- 返回: <http.ServerResponse>
返回响应对象。
【Returns the response object.】
为隐式头设置单个头值。如果该头已存在于待发送的头中,其值将被替换。这里使用字符串数组可以发送具有相同名称的多个头。非字符串值将被原样存储。因此,response.getHeader() 可能返回非字符串值。不过,非字符串值在网络传输时会被转换为字符串。相同的响应对象将返回给调用者,以便实现方法链式调用。
【Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, response.getHeader() may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.】
response.setHeader('Content-Type', 'text/html');
或者
【or】
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
当使用 response.setHeader() 设置了头部时,它们将与传递给 response.writeHead() 的任何头部合并,而传递给 response.writeHead() 的头部优先。
【When headers have been set with response.setHeader(), they will be merged
with any headers passed to response.writeHead(), with the headers passed
to response.writeHead() given precedence.】
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
如果调用 response.writeHead() 方法,而该方法之前未被调用,它会直接将提供的头部值写入网络通道,而不会在内部缓存,并且头部上的 response.getHeader() 不会产生预期的结果。如果希望逐步填充头部,同时可能进行将来的检索和修改,请使用 response.setHeader() 而不是 response.writeHead()。
【If response.writeHead() method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the response.getHeader() on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
response.setHeader() instead of response.writeHead().】
response.setTimeout(msecs[, callback])#>
msecs<number>callback<Function>- 返回: <http.ServerResponse>
将套接字的超时值设置为 msecs。如果提供了回调函数,则会将其作为监听器添加到响应对象的 'timeout' 事件上。
【Sets the Socket's timeout value to msecs. If a callback is
provided, then it is added as a listener on the 'timeout' event on
the response object.】
如果没有在请求、响应或服务器上添加 'timeout' 监听器,当超时时,套接字将被销毁。如果为请求、响应或服务器的 'timeout' 事件分配了处理程序,则必须显式处理超时的套接字。
【If no 'timeout' listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's 'timeout' events,
timed out sockets must be handled explicitly.】
response.socket#>
引用底层套接字。通常用户不需要访问此属性。特别地,由于协议解析器附加到套接字的方式,套接字不会触发 'readable' 事件。在 response.end() 之后,该属性将被置为 null。
【Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit 'readable' events
because of how the protocol parser attaches to the socket. After
response.end(), the property is nulled.】
import http from 'node:http';
const server = http.createServer((req, res) => {
const ip = res.socket.remoteAddress;
const port = res.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);const http = require('node:http');
const server = http.createServer((req, res) => {
const ip = res.socket.remoteAddress;
const port = res.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
此属性保证是 <net.Socket> 类的一个实例,<stream.Duplex> 的子类,除非用户指定了 <net.Socket> 以外的套接字类型。
【This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket>.】
response.statusCode#>
- 类型: <number> 默认值:
200
在使用隐式头(未显式调用 response.writeHead())时,此属性控制在头部刷新时发送给客户端的状态码。
【When using implicit headers (not calling response.writeHead() explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.】
response.statusCode = 404;
在响应头发送给客户端之后,此属性表示已发送的状态码。
【After response header was sent to the client, this property indicates the status code which was sent out.】
response.statusMessage#>
- 类型:<string>
在使用隐式头(不显式调用 response.writeHead())时,此属性控制在刷新头时将发送给客户端的状态消息。如果此项保持为 undefined,则使用状态码的标准消息。
【When using implicit headers (not calling response.writeHead() explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as undefined then the standard
message for the status code will be used.】
response.statusMessage = 'Not found';
在响应头发送给客户端之后,此属性表示已发送的状态消息。
【After response header was sent to the client, this property indicates the status message which was sent out.】
response.strictContentLength#>
- 类型: <boolean> 默认:
false
如果设置为 true,Node.js 将检查 Content-Length 头的值与正文的字节大小是否相等。Content-Length 头值不匹配将导致抛出一个 Error,其标识为 code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'。
【If set to true, Node.js will check whether the Content-Length
header value and the size of the body, in bytes, are equal.
Mismatching the Content-Length header value will result
in an Error being thrown, identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.】
response.uncork()#>
【See writable.uncork().】
response.writableEnded#>
- 类型:<boolean>
在调用 response.end() 之后为 true。此属性并不表示数据是否已刷新,如需检查数据是否已刷新,请改用 response.writableFinished。
【Is true after response.end() has been called. This property
does not indicate whether the data has been flushed, for this use
response.writableFinished instead.】
response.writableFinished#>
- 类型:<boolean>
如果所有数据在 'finish' 事件发出之前立即被刷新到底层系统,则为 true。
【Is true if all data has been flushed to the underlying system, immediately
before the 'finish' event is emitted.】
response.write(chunk[, encoding][, callback])#>
chunk<string> | <Buffer> | <Uint8Array>encoding<string> 默认值:'utf8'callback<Function>- 返回:<boolean>
如果调用此方法而 response.writeHead() 尚未被调用,它将切换到隐式头模式并刷新隐式头。
【If this method is called and response.writeHead() has not been called,
it will switch to implicit header mode and flush the implicit headers.】
这会发送响应主体的一部分。此方法可以被多次调用以提供主体的连续部分。
【This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.】
如果在 createServer 中将 rejectNonStandardBodyWrites 设置为 true,那么当请求方法或响应状态不支持内容时,不允许写入主体。如果尝试在 HEAD 请求或作为 204 或 304 响应的一部分写入主体,将会抛出带有 ERR_HTTP_BODY_NOT_ALLOWED 代码的同步 Error。
【If rejectNonStandardBodyWrites is set to true in createServer
then writing to the body is not allowed when the request method or response
status do not support content. If an attempt is made to write to the body for a
HEAD request or as part of a 204 or 304response, a synchronous Error
with the code ERR_HTTP_BODY_NOT_ALLOWED is thrown.】
chunk 可以是字符串或缓冲区。如果 chunk 是字符串,第二个参数指定如何将其编码为字节流。当这段数据被刷新时,会调用 callback。
这是原始的 HTTP 正文,与可能使用的更高级的多部分正文编码无关。
【This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.】
第一次调用 response.write() 时,它会将缓冲的头信息和响应体的第一块发送给客户端。第二次调用 response.write() 时,Node.js 假设数据将以流的方式发送,并会单独发送新数据。也就是说,响应会缓冲到响应体的第一块为止。
【The first time response.write() is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time response.write() is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.】
如果所有数据都成功刷新到内核缓冲区,则返回 true。如果所有或部分数据被排队在用户内存中,则返回 false。当缓冲区再次空闲时,会触发 'drain' 事件。
【Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in user memory.
'drain' will be emitted when the buffer is free again.】
response.writeContinue()#>
向客户端发送 HTTP/1.1 100 Continue 消息,表示应该发送请求体。请参见 Server 上的 'checkContinue' 事件。
【Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the 'checkContinue' event on
Server.】
response.writeEarlyHints(hints[, callback])#>
hints<Object>callback<Function>
向客户端发送 HTTP/1.1 103 Early Hints 消息,并带有 Link 头,指示用户代理可以预加载/预连接链接的资源。hints 是一个包含要随 early hints 消息发送的头值的对象。可选的 callback 参数将在响应消息写入完成后被调用。
【Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The hints is an object containing the values of headers to be sent with
early hints message. The optional callback argument will be called when
the response message has been written.】
示例
const earlyHintsLink = '</styles.css>; rel=preload; as=style';
response.writeEarlyHints({
'link': earlyHintsLink,
});
const earlyHintsLinks = [
'</styles.css>; rel=preload; as=style',
'</scripts.js>; rel=preload; as=script',
];
response.writeEarlyHints({
'link': earlyHintsLinks,
'x-trace-id': 'id for diagnostics',
});
const earlyHintsCallback = () => console.log('early hints message sent');
response.writeEarlyHints({
'link': earlyHintsLinks,
}, earlyHintsCallback);
response.writeHead(statusCode[, statusMessage][, headers])#>
statusCode<number>statusMessage<string>headers<Object> | <Array>- 返回: <http.ServerResponse>
向请求发送响应头。状态码是一个三位数的 HTTP 状态码,例如 404。最后一个参数 headers 是响应头。可选地,可以将人类可读的 statusMessage 作为第二个参数提供。
【Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404. The last argument, headers, are the response headers.
Optionally one can give a human-readable statusMessage as the second
argument.】
headers 可能是一个 Array,其键和值在同一个列表中。它 不是 一个元组列表。因此,偶数索引是键,奇数索引是对应的值。这个数组的格式与 request.rawHeaders 相同。
返回对 ServerResponse 的引用,以便可以进行链式调用。
【Returns a reference to the ServerResponse, so that calls can be chained.】
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
})
.end(body);
此方法只能在消息上调用一次,并且必须在调用 response.end() 之前调用。
【This method must only be called once on a message and it must
be called before response.end() is called.】
如果在调用此函数之前调用 response.write() 或 response.end(),将会计算隐式/可变头并调用此函数。
【If response.write() or response.end() are called before calling
this, the implicit/mutable headers will be calculated and call this function.】
当使用 response.setHeader() 设置了头部时,它们将与传递给 response.writeHead() 的任何头部合并,而传递给 response.writeHead() 的头部优先。
【When headers have been set with response.setHeader(), they will be merged
with any headers passed to response.writeHead(), with the headers passed
to response.writeHead() given precedence.】
如果调用此方法而 response.setHeader() 尚未被调用,它将直接将提供的头部值写入网络通道,而不会在内部缓存,并且头部上的 response.getHeader() 不会产生预期的结果。如果希望逐步填充头部,并在将来可能进行检索和修改,请改用 response.setHeader()。
【If this method is called and response.setHeader() has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the response.getHeader() on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
response.setHeader() instead.】
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
Content-Length 是按字节读取的,而不是按字符。使用 Buffer.byteLength() 来确定正文的字节长度。Node.js 会检查 Content-Length 与已传输正文的长度是否相等。
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
response.writeProcessing()#>
向客户端发送 HTTP/1.1 102 处理中消息,表示应该发送请求正文。
【Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.】
类:http.IncomingMessage#>
【Class: http.IncomingMessage】
- 扩展自: <stream.Readable>
IncomingMessage 对象由 http.Server 或 http.ClientRequest 创建,并分别作为 'request' 和 'response' 事件的第一个参数传递。它可用于访问响应状态、头信息和数据。
【An IncomingMessage object is created by http.Server or
http.ClientRequest and passed as the first argument to the 'request'
and 'response' event respectively. It may be used to access response
status, headers, and data.】
与其 socket 值不同,socket 是 <stream.Duplex> 的子类,IncomingMessage 本身继承自 <stream.Readable> 并单独创建,用于解析和发送传入的 HTTP 头和负载,因为在使用 keep-alive 的情况下,底层 socket 可能会被多次重用。
【Different from its socket value which is a subclass of <stream.Duplex>, the
IncomingMessage itself extends <stream.Readable> and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.】
事件:'aborted'#>
【Event: 'aborted'】
'close' 事件。当请求被中止时触发。
【Emitted when the request has been aborted.】
事件:'close'#>
【Event: 'close'】
当请求完成时触发。
【Emitted when the request has been completed.】
message.aborted#>
稳定性:0 - 已弃用。请检查 <stream.Readable> 的
message.destroyed。
- 类型:<boolean>
如果请求已被中止,message.aborted 属性将为 true。
【The message.aborted property will be true if the request has
been aborted.】
message.complete#>
- 类型:<boolean>
message.complete 属性将在接收到完整的 HTTP 消息并成功解析后为 true。
【The message.complete property will be true if a complete HTTP message has
been received and successfully parsed.】
这个属性特别有用,它可以用来判断客户端或服务器在连接被终止前是否已完整地发送消息:
【This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:】
const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST',
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
message.connection#>
message.socket。message.socket 的别名。
【Alias for message.socket.】
message.destroy([error])#>
对接收到 IncomingMessage 的套接字调用 destroy()。如果提供了 error,套接字上会触发 'error' 事件,并且 error 会作为参数传递给该事件的任何监听器。
【Calls destroy() on the socket that received the IncomingMessage. If error
is provided, an 'error' event is emitted on the socket and error is passed
as an argument to any listeners on the event.】
message.headers#>
- 类型: <Object>
请求/响应头对象。
【The request/response headers object.】
头部名称和值的键值对。头部名称使用小写。
【Key-value pairs of header names and values. Header names are lower-cased.】
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.headers);
原始头中的重复项处理方法如下,具体取决于头名称:
【Duplicates in raw headers are handled in the following ways, depending on the header name:】
- 会丢弃
age、authorization、content-length、content-type、etag、expires、from、host、if-modified-since、if-unmodified-since、last-modified、location、max-forwards、proxy-authorization、referer、retry-after、server或user-agent的重复项。要允许上述列出的头部重复值被合并,请在http.request()和http.createServer()中使用选项joinDuplicateHeaders。更多信息参见 RFC 9110 第 5.3 节。 set-cookie总是一个数组。重复项会被添加到数组中。- 对于重复的
cookie头,值会使用;连接在一起。 - 对于所有其他头部,值将使用
,连接在一起。
message.headersDistinct#>
- 类型: <Object>
类似于 message.headers,但没有连接逻辑,且其值始终是字符串数组,即使是只接收一次的头也如此。
【Similar to message.headers, but there is no join logic and the values are
always arrays of strings, even for headers received just once.】
// Prints something like:
//
// { 'user-agent': ['curl/7.22.0'],
// host: ['127.0.0.1:8000'],
// accept: ['*/*'] }
console.log(request.headersDistinct);
message.httpVersion#>
- 类型:<string>
在服务器请求的情况下,由客户端发送的 HTTP 版本。在客户端响应的情况下,为所连接服务器的 HTTP 版本。可能是 '1.1' 或 '1.0'。
【In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either '1.1' or '1.0'.】
此外,message.httpVersionMajor 是第一个整数,而 message.httpVersionMinor 是第二个整数。
【Also message.httpVersionMajor is the first integer and
message.httpVersionMinor is the second.】
message.method#>
- 类型:<string>
仅对从 http.Server 获取的请求有效。
请求方法,字符串形式。只读。示例:'GET'、'DELETE'。
【The request method as a string. Read only. Examples: 'GET', 'DELETE'.】
message.rawHeaders#>
- 类型: <string[]>
原始请求/响应头完全按照收到的方式列出。
【The raw request/response headers list exactly as they were received.】
键和值在同一个列表中。它 不是 元组的列表。因此,偶数位置是键,奇数位置是对应的值。
【The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.】
标头名称不小写,重复项不合并。
【Header names are not lowercased, and duplicates are not merged.】
// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*/*' ]
console.log(request.rawHeaders);
message.rawTrailers#>
- 类型: <string[]>
原始请求/响应的 trailer 键和值,与接收时完全相同。仅在 'end' 事件时填充。
【The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end' event.】
message.setTimeout(msecs[, callback])#>
msecs<number>callback<Function>- 返回:<http.IncomingMessage>
调用 message.socket.setTimeout(msecs, callback)。
【Calls message.socket.setTimeout(msecs, callback).】
message.socket#>
与该连接相关的 net.Socket 对象。
【The net.Socket object associated with the connection.】
在支持 HTTPS 的情况下,使用 request.socket.getPeerCertificate() 获取客户端的认证详细信息。
【With HTTPS support, use request.socket.getPeerCertificate() to obtain the
client's authentication details.】
这个属性保证是 <net.Socket> 类的一个实例,它是 <stream.Duplex> 的子类,除非用户指定了除 <net.Socket> 之外的套接字类型,或者在内部被置为 null。
【This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket> or internally nulled.】
message.statusCode#>
- 类型:<number>
仅适用于从 http.ClientRequest 获取的响应。
三位数的 HTTP 响应状态码。例如 404。
【The 3-digit HTTP response status code. E.G. 404.】
message.statusMessage#>
- 类型:<string>
仅适用于从 http.ClientRequest 获取的响应。
HTTP 响应状态消息(原因短语)。例如:OK 或 Internal Server Error。
【The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.】
message.trailers#>
- 类型: <Object>
请求/响应尾部对象。仅在 'end' 事件时填充。
【The request/response trailers object. Only populated at the 'end' event.】
message.trailersDistinct#>
- 类型: <Object>
类似于 message.trailers,但没有连接逻辑,值始终是字符串数组,即使是只接收一次的头信息也一样。仅在 'end' 事件时填充。
【Similar to message.trailers, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
Only populated at the 'end' event.】
message.url#>
- 类型:<string>
仅对从 http.Server 获取的请求有效。
请求 URL 字符串。它仅包含实际 HTTP 请求中存在的 URL。请看以下请求:
【Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:】
GET /status?name=ryan HTTP/1.1
Accept: text/plain
要将网址解析为它的部分:
【To parse the URL into its parts:】
new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
当 request.url 是 '/status?name=ryan' 且 process.env.HOST 未定义时:
【When request.url is '/status?name=ryan' and process.env.HOST is undefined:】
$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
href: 'http://localhost/status?name=ryan',
origin: 'http://localhost',
protocol: 'http:',
username: '',
password: '',
host: 'localhost',
hostname: 'localhost',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
确保将 process.env.HOST 设置为服务器的主机名,或者考虑完全替换这一部分。如果使用 req.headers.host,请确保使用适当的验证,因为客户端可能会指定自定义的 Host 头。
【Ensure that you set process.env.HOST to the server's host name, or consider
replacing this part entirely. If using req.headers.host, ensure proper
validation is used, as clients may specify a custom Host header.】
类:http.OutgoingMessage#>
【Class: http.OutgoingMessage】
- 扩展:<Stream>
此类作为 http.ClientRequest 和 http.ServerResponse 的父类。从 HTTP 事务参与者的角度来看,它是一个抽象的外发消息。
【This class serves as the parent class of http.ClientRequest
and http.ServerResponse. It is an abstract outgoing message from
the perspective of the participants of an HTTP transaction.】
事件:'drain'#>
【Event: 'drain'】
当消息的缓冲区再次空闲时触发。
【Emitted when the buffer of the message is free again.】
事件:'finish'#>
【Event: 'finish'】
当传输成功完成时触发。
【Emitted when the transmission is finished successfully.】
事件:'prefinish'#>
【Event: 'prefinish'】
在调用 outgoingMessage.end() 后触发。 当事件被触发时,所有数据都已被处理,但不一定已完全刷新。
【Emitted after outgoingMessage.end() is called.
When the event is emitted, all data has been processed but not necessarily
completely flushed.】
outgoingMessage.addTrailers(headers)#>
headers<Object>
添加 HTTP 尾标(标头,但在消息末尾)到消息。
【Adds HTTP trailers (headers but at the end of the message) to the message.】
只有在消息使用分块编码时,才会发送尾部信息。如果不是,尾部信息将被静默丢弃。
【Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.】
HTTP 要求发送 Trailer 头以发出尾部信息,其值中包含一个头字段名称的列表,例如。
【HTTP requires the Trailer header to be sent to emit trailers,
with a list of header field names in its value, e.g.】
message.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
message.write(fileData);
message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
message.end();
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
outgoingMessage.appendHeader(name, value)#>
name<string> 头部名称value<string> | <string[]> 头部值- 返回:<this>
将单个标头值附加到标头对象。
【Append a single header value to the header object.】
如果值是数组,这相当于多次调用此方法。
【If the value is an array, this is equivalent to calling this method multiple times.】
如果该头部没有以前的值,这等同于调用 outgoingMessage.setHeader(name, value)。
【If there were no previous values for the header, this is equivalent to calling
outgoingMessage.setHeader(name, value).】
根据 options.uniqueHeaders 的值,当客户端请求或服务器创建时,最终会导致该头部被发送多次,或者只发送一次且其值使用 ; 连接。
【Depending of the value of options.uniqueHeaders when the client request or the
server were created, this will end up in the header being sent multiple times or
a single time with values joined using ; .】
outgoingMessage.connection#>
outgoingMessage.socket。【Alias of outgoingMessage.socket.】
outgoingMessage.cork()#>
【See writable.cork().】
outgoingMessage.destroy([error])#>
销毁消息。一旦套接字与消息关联并且已连接,该套接字也将被销毁。
【Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well.】
outgoingMessage.end(chunk[, encoding][, callback])#>
chunk<string> | <Buffer> | <Uint8Array>encoding<string> 可选,默认:utf8callback<Function> 可选- 返回:<this>
完成发送出站消息。如果消息体的任何部分尚未发送,它会将这些部分刷新到底层系统。如果消息是分块的,它将发送终止块 `0
`,并发送尾部信息(如果有)。
【Finishes the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will
send the terminating chunk 0\r\n\r\n, and send the trailers (if any).】
如果指定了 chunk,等同于先调用 outgoingMessage.write(chunk, encoding),然后调用 outgoingMessage.end(callback)。
【If chunk is specified, it is equivalent to calling
outgoingMessage.write(chunk, encoding), followed by
outgoingMessage.end(callback).】
如果提供了 callback,当消息完成时它将被调用(相当于 'finish' 事件的监听器)。
【If callback is provided, it will be called when the message is finished
(equivalent to a listener of the 'finish' event).】
outgoingMessage.flushHeaders()#>
刷新消息标头。
【Flushes the message headers.】
出于效率考虑,Node.js 通常会缓存消息头,直到调用 outgoingMessage.end() 或写入消息数据的第一个片段。然后,它会尝试将头部和数据打包到一个 TCP 数据包中。
【For efficiency reason, Node.js normally buffers the message headers
until outgoingMessage.end() is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.】
通常这是希望的(可以节省一次 TCP 往返),但当第一次数据可能要很久之后才发送时就不适用。outgoingMessage.flushHeaders() 会绕过这个优化并启动消息发送。
【It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. outgoingMessage.flushHeaders()
bypasses the optimization and kickstarts the message.】
outgoingMessage.getHeader(name)#>
name<string> 头部名称- 返回:数字 | 字符串 | 字符串[] | 未定义
获取指定名称的 HTTP 头的值。如果该头未设置,返回的值将是 undefined。
【Gets the value of the HTTP header with the given name. If that header is not
set, the returned value will be undefined.】
outgoingMessage.getHeaderNames()#>
- 返回值: <string[]>
返回一个包含当前要发送的唯一头名称的数组。所有名称均为小写。
【Returns an array containing the unique names of the current outgoing headers. All names are lowercase.】
outgoingMessage.getHeaders()#>
- 返回:<Object>
返回当前发出的头部的浅拷贝。由于使用的是浅拷贝,数组值可以在不额外调用各种与头部相关的 HTTP 模块方法的情况下被修改。返回对象的键是头部名称,值是相应的头部值。所有头部名称都是小写的。
【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.】
outgoingMessage.getHeaders() 方法返回的对象并没有从 JavaScript 的 Object 原型继承。这意味着典型的 Object 方法,例如 obj.toString()、obj.hasOwnProperty() 等,并未定义,无法使用。
【The object returned by the outgoingMessage.getHeaders() method does
not prototypically inherit from the JavaScript Object. This means that
typical Object methods such as obj.toString(), obj.hasOwnProperty(),
and others are not defined and will not work.】
outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
outgoingMessage.hasHeader(name)#>
如果由 name 标识的头当前已在发送的头中设置,则返回 true。头名称不区分大小写。
【Returns true if the header identified by name is currently set in the
outgoing headers. The header name is case-insensitive.】
const hasContentType = outgoingMessage.hasHeader('content-type');
outgoingMessage.headersSent#>
- 类型:<boolean>
只读。如果头信息已发送,则为 true,否则为 false。
【Read-only. true if the headers were sent, otherwise false.】
outgoingMessage.pipe()#>
重写了继承自旧版 Stream 类的 stream.pipe() 方法,而 Stream 是 http.OutgoingMessage 的父类。
【Overrides the stream.pipe() method inherited from the legacy Stream class
which is the parent class of http.OutgoingMessage.】
调用此方法会抛出 Error,因为 outgoingMessage 是一个只写流。
【Calling this method will throw an Error because outgoingMessage is a
write-only stream.】
outgoingMessage.removeHeader(name)#>
name<string> 头部名称
删除排队等待隐式发送的标头。
【Removes a header that is queued for implicit sending.】
outgoingMessage.removeHeader('Content-Encoding');
outgoingMessage.setHeader(name, value)#>
name<string> 头部名称value<number> | <string> | <string[]> 请求头的值- 返回:<this>
设置单个头部值。如果要发送的头部中已存在该头部,其值将被替换。使用字符串数组可以发送具有相同名称的多个头部。
【Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.】
outgoingMessage.setHeaders(headers)#>
为隐式头设置多个头值。headers 必须是 Headers 的实例或 Map,如果待发送的头中已经存在该头,它的值将被替换。
【Sets multiple header values for implicit headers.
headers must be an instance of Headers or Map,
if a header already exists in the to-be-sent headers,
its value will be replaced.】
const headers = new Headers({ foo: 'bar' });
outgoingMessage.setHeaders(headers);
或者
【or】
const headers = new Map([['foo', 'bar']]);
outgoingMessage.setHeaders(headers);
当使用 outgoingMessage.setHeaders() 设置了头信息时,它们会与传递给 response.writeHead() 的任何头信息合并,并且传递给 response.writeHead() 的头信息具有优先权。
【When headers have been set with outgoingMessage.setHeaders(),
they will be merged with any headers passed to response.writeHead(),
with the headers passed to response.writeHead() given precedence.】
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
const headers = new Headers({ 'Content-Type': 'text/html' });
res.setHeaders(headers);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
outgoingMessage.setTimeout(msecs[, callback])#>
msecs<number>callback<Function> 可选函数,在超时发生时调用。与绑定timeout事件相同。- 返回:<this>
一旦套接字与消息关联并且已连接,socket.setTimeout() 将被调用,第一个参数为 msecs。
【Once a socket is associated with the message and is connected,
socket.setTimeout() will be called with msecs as the first parameter.】
outgoingMessage.socket#>
引用底层套接字。通常,用户不希望访问此属性。
【Reference to the underlying socket. Usually, users will not want to access this property.】
在调用 outgoingMessage.end() 之后,该属性将被置为空。
【After calling outgoingMessage.end(), this property will be nulled.】
outgoingMessage.uncork()#>
【See writable.uncork()】
outgoingMessage.writableCorked#>
- 类型:<number>
outgoingMessage.cork() 被调用的次数。
【The number of times outgoingMessage.cork() has been called.】
outgoingMessage.writableEnded#>
- 类型:<boolean>
如果已调用 outgoingMessage.end(),则为 true。此属性并不表示数据是否已刷新。为此,请使用 message.writableFinished。
【Is true if outgoingMessage.end() has been called. This property does
not indicate whether the data has been flushed. For that purpose, use
message.writableFinished instead.】
outgoingMessage.writableFinished#>
- 类型:<boolean>
如果所有数据都已刷新到底层系统,则为 true。
【Is true if all data has been flushed to the underlying system.】
outgoingMessage.writableHighWaterMark#>
- 类型:<number>
如果已分配,则为底层套接字的 highWaterMark。否则,当 writable.write() 开始返回 false 时的默认缓冲级别(16384)。
【The highWaterMark of the underlying socket if assigned. Otherwise, the default
buffer level when writable.write() starts returning false (16384).】
outgoingMessage.writableLength#>
- 类型:<number>
缓冲的字节数。
【The number of buffered bytes.】
outgoingMessage.writableObjectMode#>
- 类型:<boolean>
总是 false。
【Always false.】
outgoingMessage.write(chunk[, encoding][, callback])#>
chunk<string> | <Buffer> | <Uint8Array>encoding<string> 默认:utf8callback<Function>- 返回:<boolean>
发送一段主体内容。此方法可以被多次调用。
【Sends a chunk of the body. This method can be called multiple times.】
encoding 参数仅在 chunk 是字符串时才相关。默认值为 'utf8'。
【The encoding argument is only relevant when chunk is a string. Defaults to
'utf8'.】
callback 参数是可选的,当这一数据块被刷新时将被调用。
【The callback argument is optional and will be called when this chunk of data
is flushed.】
如果整个数据已成功刷新到内核缓冲区,则返回 true。如果全部或部分数据被排入用户内存,则返回 false。当缓冲区再次空闲时,会触发 'drain' 事件。
【Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in the user
memory. The 'drain' event will be emitted when the buffer is free again.】
http.METHODS#>
- 类型: <string[]>
解析器支持的 HTTP 方法列表。
【A list of the HTTP methods that are supported by the parser.】
http.STATUS_CODES#>
- 类型: <Object>
所有标准 HTTP 响应状态码的集合,以及每个状态码的简短描述。例如,http.STATUS_CODES[404] === 'Not Found'。
【A collection of all the standard HTTP response status codes, and the
short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.】
http.createServer([options][, requestListener])#>
options<Object>connectionsCheckingInterval:设置以毫秒为单位的时间间隔,用于检查不完整请求中的请求和头部超时。 默认值:30000。headersTimeout:设置从客户端接收完整 HTTP 头部的超时时间,单位为毫秒。更多信息请参见server.headersTimeout。默认值:60000。highWaterMark<number> 可选择覆盖所有socket的readableHighWaterMark和writableHighWaterMark。这会影响IncomingMessage和ServerResponse的highWaterMark属性。默认值: 参见stream.getDefaultHighWaterMark()。insecureHTTPParser<boolean> 如果设置为true,将使用启用宽松标志的 HTTP 解析器。应尽量避免使用不安全的解析器。更多信息请参见--insecure-http-parser。默认值:false。IncomingMessage<http.IncomingMessage> 指定要使用的IncomingMessage类。对于扩展原始的IncomingMessage非常有用。默认值:IncomingMessage.joinDuplicateHeaders<boolean> 如果设置为true,此选项允许将请求中多个头的字段行值使用逗号(,)连接,而不是丢弃重复项。有关更多信息,请参阅message.headers。默认值:false。- 'keepAlive' <boolean> 如果设置为“true”,则在接收到新入连接后立即启用该套接字的保持活功能,类似于['socket.setKeepAlive([enable][, initialDelay])']['socket.setKeepAlive(enable, initialDelay)']。 默认: 'false'。
keepAliveInitialDelay<number> 如果设置为正数,它会设置在空闲套接字上发送第一个保活探测之前的初始延迟。 默认值:0。keepAliveTimeout:服务器在完成最后一次响应写入后,需要等待额外传入数据的空闲时间(以毫秒为单位),超时后连接将被关闭。有关更多信息,请参阅server.keepAliveTimeout。默认值:5000。maxHeaderSize<number> 可选择覆盖此服务器接收请求时--max-http-header-size的值,即请求头的最大长度(以字节为单位)。默认值: 16384(16 KiB)。noDelay<boolean> 如果设置为true,在收到新的传入连接后会立即禁用 Nagle 算法。默认值:true。requestTimeout:设置从客户端接收整个请求的超时时间,单位为毫秒。更多信息请参见server.requestTimeout。默认值:300000。requireHostHeader<boolean> 如果设置为true,它会强制服务器对任何缺少 Host 头的 HTTP/1.1 请求消息返回 400(错误请求)状态码(如规范所规定)。 默认值:true。ServerResponse<http.ServerResponse> 指定要使用的ServerResponse类。对于扩展原始的ServerResponse非常有用。默认值:ServerResponse。shouldUpgradeCallback(request)<Function> 一个回调函数,它接收传入的请求并返回一个布尔值,用于控制应接受哪些升级尝试。被接受的升级将触发'upgrade'事件(如果没有注册监听器,其套接字将被销毁),而被拒绝的升级将像任何非升级请求一样触发'request'事件。此选项默认值为() => server.listenerCount('upgrade') > 0。uniqueHeaders<Array> 一份只应发送一次的响应头列表。如果头的值是数组,数组项将使用;连接。rejectNonStandardBodyWrites<boolean> 如果设置为true,在向没有正文的 HTTP 响应写入内容时将抛出错误。 默认值:false。
requestListener<Function>- 返回值:<http.Server>
返回一个新的 http.Server 实例。
【Returns a new instance of http.Server.】
requestListener 是一个函数,会自动添加到 'request' 事件中。
【The requestListener is a function which is automatically
added to the 'request' event.】
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);const http = require('node:http');
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);const http = require('node:http');
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
http.get(options[, callback])#>
http.get(url[, options][, callback])#>
url<string> | <URL>options<Object> 接受与http.request()相同的options,默认情况下方法设置为 GET。callback<Function>- 返回: <http.ClientRequest>
由于大多数请求都是没有请求体的 GET 请求,Node.js 提供了这个便捷方法。该方法与 http.request() 的唯一区别在于,它默认将方法设置为 GET,并自动调用 req.end()。回调函数必须注意处理响应数据,原因见 http.ClientRequest 节。
【Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
http.request() is that it sets the method to GET by default and calls req.end()
automatically. The callback must take care to consume the response
data for reasons stated in http.ClientRequest section.】
callback 会被调用,并且传入一个参数,该参数是 http.IncomingMessage 的实例。
【The callback is invoked with a single argument that is an instance of
http.IncomingMessage.】
获取 JSON 的示例:
【JSON fetching example:】
http.get('http://localhost:8000/', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
http.globalAgent#>
- 类型: <http.Agent>
Agent 的全局实例,用作所有 HTTP 客户端请求的默认值。与默认的 Agent 配置不同,它启用了 keepAlive 并设置了 5 秒的超时。
【Global instance of Agent which is used as the default for all HTTP client
requests. Diverges from a default Agent configuration by having keepAlive
enabled and a timeout of 5 seconds.】
http.maxHeaderSize#>
- 类型:<number>
只读属性,指定 HTTP 头允许的最大字节数。默认值为 16 KiB。可以使用 --max-http-header-size CLI 选项进行配置。
【Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16 KiB. Configurable using the --max-http-header-size CLI
option.】
可以通过传递 maxHeaderSize 选项来覆盖服务器和客户端请求的此设置。
【This can be overridden for servers and client requests by passing the
maxHeaderSize option.】
http.request(options[, callback])#>
http.request(url[, options][, callback])#>
url<string> | <URL>options<Object>agent<http.Agent> | <boolean> 控制Agent行为。可能的取值:undefined(默认):对该主机和端口使用http.globalAgent。Agent对象:明确使用传入的Agent。false:会使用具有默认值的新Agent。
auth<string> 基本身份验证('user:password'),用于计算 Authorization 头。createConnection<Function> 一个函数,用于在未使用agent选项时生成用于请求的 socket/流。可以使用它来避免仅为了重写默认的createConnection函数而创建自定义Agent类。有关更多详细信息,请参见agent.createConnection()。任何Duplex流都是有效的返回值。defaultPort<number> 协议的默认端口。默认值: 如果使用Agent,则为agent.defaultPort,否则为undefined。family<number> 在解析host或hostname时使用的 IP 地址类型。有效值为4或6。如果未指定,将同时使用 IPv4 和 IPv6。headers<Object> | <Array> 一个包含请求头的对象或字符串数组。数组的格式与message.rawHeaders相同。hints<number> 可选dns.lookup()提示。host<string> 用于发出请求的服务器的域名或 IP 地址。默认值:'localhost'。hostname<string> 是host的别名。为了支持url.parse(),如果同时指定了host和hostname,将使用hostname。insecureHTTPParser<boolean> 如果设置为true,将使用启用了宽松标志的 HTTP 解析器。应尽量避免使用不安全的解析器。更多信息请参见--insecure-http-parser。 默认值:falsejoinDuplicateHeaders<boolean> 它将请求中多个头的字段行值用,连接,而不是丢弃重复值。更多信息请参见message.headers。 默认值:false。localAddress<string> 用于网络连接的本地绑定接口。localPort<number> 要连接使用的本地端口。lookup<Function> 自定义查找函数。默认值:dns.lookup()。maxHeaderSize<number> 可选择覆盖--max-http-header-size(从服务器接收的响应头的最大字节长度)的值。默认值: 16384(16 KiB)。method<string> 一个字符串,指定 HTTP 请求方法。默认值:'GET'。path<string> 请求路径。如果有查询字符串,也应包含在内。例如'/index.html?page=12'。当请求路径包含非法字符时会抛出异常。目前,仅空格会被拒绝,但未来可能会有所改变。默认值:'/'。port<number> 远程服务器的端口。默认值: 如果设置了defaultPort则使用,否则为80。protocol<string> 使用的协议。默认值:'http:'。setDefaultHeaders<boolean>:指定是否自动添加默认头,如Connection、Content-Length、Transfer-Encoding和Host。如果设置为false,则所有必要的头都必须手动添加。默认值为true。setHost<boolean>:指定是否自动添加Host头。如果提供,则会覆盖setDefaultHeaders。默认值为true。signal<AbortSignal>:一个可以用于中止正在进行的请求的 AbortSignal。socketPath<string> Unix 域套接字。如果指定了host或port,则不能使用,因为它们指定的是 TCP 套接字。timeout<number>:一个数字,指定套接字超时的毫秒数。这将设置套接字连接前的超时时间。uniqueHeaders<Array> 一份只应发送一次的请求头列表。如果请求头的值是数组,数组中的条目将使用;连接。
callback<Function>- 返回: <http.ClientRequest>
socket.connect() 中的 options 也受支持。
Node.js 为每个服务器维护多个连接以进行 HTTP 请求。此功能允许用户透明地发起请求。
【Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.】
url 可以是字符串或 URL 对象。如果 url 是字符串,它会自动使用 new URL() 解析。如果它是 URL 对象,它将自动转换为普通的 options 对象。
如果同时指定了 url 和 options,这些对象将会合并,其中 options 的属性优先。
【If both url and options are specified, the objects are merged, with the
options properties taking precedence.】
可选的 callback 参数将作为 'response' 事件的单次监听器添加。
【The optional callback parameter will be added as a one-time listener for
the 'response' event.】
http.request() 返回一个 http.ClientRequest 类的实例。ClientRequest 实例是一个可写流。如果需要使用 POST 请求上传文件,则可以写入 ClientRequest 对象。
import http from 'node:http';
import { Buffer } from 'node:buffer';
const postData = JSON.stringify({
'msg': 'Hello World!',
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();const http = require('node:http');
const postData = JSON.stringify({
'msg': 'Hello World!',
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
在示例中调用了 req.end()。使用 http.request() 时必须始终调用 req.end() 来表示请求的结束——即使没有数据写入请求体。
【In the example req.end() was called. With http.request() one
must always call req.end() to signify the end of the request -
even if there is no data being written to the request body.】
如果在请求过程中遇到任何错误(无论是 DNS 解析、TCP 层错误,还是实际的 HTTP 解析错误),都会在返回的请求对象上触发 'error' 事件。与所有 'error' 事件一样,如果没有注册监听器,该错误将会被抛出。
【If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an 'error' event is emitted
on the returned request object. As with all 'error' events, if no listeners
are registered the error will be thrown.】
有一些特殊的标头需要注意。
【There are a few special headers that should be noted.】
- 发送“Connection: keep-alive”将通知 Node.js,连接服务器应保持直到下一次请求。
- 发送 'Content-Length' 头将会禁用默认的分块传输编码。
- 发送 'Expect' 头会立即发送请求头。通常,在发送 'Expect: 100-continue' 时,应同时设置超时和
'continue'事件的监听器。有关更多信息,请参阅 RFC 2616 第 8.2.3 节。 - 发送授权头将覆盖使用
auth选项来计算基本身份验证。
使用 URL 作为 options 的示例:
【Example using a URL as options:】
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
在一次成功的请求中,将按以下顺序触发以下事件:
【In a successful request, the following events will be emitted in the following order:】
'socket''response''data'可以在res对象上出现任意次数(如果响应体为空,例如在大多数重定向中,'data'将根本不会被触发)res对象上的'end'
'close'
在连接错误的情况下,将触发以下事件:
【In the case of a connection error, the following events will be emitted:】
'socket''error''close'
在响应收到之前如果过早关闭连接,将按以下顺序触发以下事件:
【In the case of a premature connection close before the response is received, the following events will be emitted in the following order:】
'socket''error',错误信息为'Error: socket hang up',错误代码为'ECONNRESET''close'
在响应接收后,如果连接过早关闭,将按以下顺序触发以下事件:
【In the case of a premature connection close after the response is received, the following events will be emitted in the following order:】
'socket''response''data'在res对象上可以出现任意次数
- (连接已关闭)
res对象上的'aborted''close'res对象上的'error',错误信息为'Error: aborted',错误代码为'ECONNRESET'res对象上的'close'
如果在分配套接字之前调用 req.destroy(),将按以下顺序触发以下事件:
【If req.destroy() is called before a socket is assigned, the following
events will be emitted in the following order:】
- (此处调用了
req.destroy()) 'error'错误,其消息为'Error: socket hang up',代码为'ECONNRESET',或者是调用req.destroy()时产生的错误'close'
如果在连接成功之前调用 req.destroy(),将按以下顺序触发以下事件:
【If req.destroy() is called before the connection succeeds, the following
events will be emitted in the following order:】
'socket'- (此处调用了
req.destroy()) 'error'错误,其消息为'Error: socket hang up',代码为'ECONNRESET',或者是调用req.destroy()时产生的错误'close'
如果在收到响应后调用 req.destroy(),将按以下顺序触发以下事件:
【If req.destroy() is called after the response is received, the following
events will be emitted in the following order:】
'socket''response''data'在res对象上可以出现任意次数
- (此处调用了
req.destroy()) res对象上的'aborted''close'res对象上的'error'错误,错误信息为'Error: aborted',错误代码为'ECONNRESET',或者是用于调用req.destroy()的错误res对象上的'close'
如果在分配套接字之前调用 req.abort(),将按以下顺序触发以下事件:
【If req.abort() is called before a socket is assigned, the following
events will be emitted in the following order:】
- (此处调用了
req.abort()) 'abort''close'
如果在连接成功之前调用 req.abort(),将按以下顺序触发以下事件:
【If req.abort() is called before the connection succeeds, the following
events will be emitted in the following order:】
'socket'- (此处调用了
req.abort()) 'abort''error',错误信息为'Error: socket hang up',错误代码为'ECONNRESET''close'
如果在收到响应后调用 req.abort(),将按以下顺序触发以下事件:
【If req.abort() is called after the response is received, the following
events will be emitted in the following order:】
'socket''response''data'在res对象上可以出现任意次数
- (此处调用了
req.abort()) 'abort'res对象上的'aborted'res对象上的'error',错误信息为'Error: aborted',错误代码为'ECONNRESET'。'close'res对象上的'close'
设置 timeout 选项或使用 setTimeout() 函数不会中止请求,也不会做其他任何事情,只会添加一个 'timeout' 事件。
【Setting the timeout option or using the setTimeout() function will
not abort the request or do anything besides add a 'timeout' event.】
传递一个 AbortSignal 然后在对应的 AbortController 上调用 abort(),其行为将与对请求调用 .destroy() 相同。具体来说,将触发 'error' 事件,并伴随一条错误消息 'AbortError: The operation was aborted'、错误代码 'ABORT_ERR',以及(如果提供了的话)cause。
【Passing an AbortSignal and then calling abort() on the corresponding
AbortController will behave the same way as calling .destroy() on the
request. Specifically, the 'error' event will be emitted with an error with
the message 'AbortError: The operation was aborted', the code 'ABORT_ERR'
and the cause, if one was provided.】
http.validateHeaderName(name[, label])#>
对提供的 name 执行低级验证,这些验证在调用 res.setHeader(name, value) 时进行。
【Performs the low-level validations on the provided name that are done when
res.setHeader(name, value) is called.】
将非法值作为 name 传递会导致抛出 TypeError,错误代码为 code: 'ERR_INVALID_HTTP_TOKEN'。
【Passing illegal value as name will result in a TypeError being thrown,
identified by code: 'ERR_INVALID_HTTP_TOKEN'.】
在向 HTTP 请求或响应传递头信息之前,不必使用此方法。HTTP 模块会自动验证这些头信息。
【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.】
示例:
【Example:】
import { validateHeaderName } from 'node:http';
try {
validateHeaderName('');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}const { validateHeaderName } = require('node:http');
try {
validateHeaderName('');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}
http.validateHeaderValue(name, value)#>
对提供的 value 执行低级验证,这些验证在调用 res.setHeader(name, value) 时进行。
【Performs the low-level validations on the provided value that are done when
res.setHeader(name, value) is called.】
将非法值作为 value 传递会导致抛出 TypeError。
【Passing illegal value as value will result in a TypeError being thrown.】
- 未定义值错误由
code: 'ERR_HTTP_INVALID_HEADER_VALUE'标识。 - 无效值字符错误由
code: 'ERR_INVALID_CHAR'标识。
在向 HTTP 请求或响应传递头信息之前,不必使用此方法。HTTP 模块会自动验证这些头信息。
【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:】
import { validateHeaderValue } from 'node:http';
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}const { validateHeaderValue } = require('node:http');
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}
http.setMaxIdleHTTPParsers(max)#>
max<number> 默认:1000。
设置最大空闲 HTTP 解析器数。
【Set the maximum number of idle HTTP parsers.】
类:WebSocket#>
【Class: WebSocket】
一个与浏览器兼容的 WebSocket 实现。
【A browser-compatible implementation of WebSocket.】
内置代理支持#>
【Built-in Proxy Support】
当 Node.js 创建全局代理时,如果 NODE_USE_ENV_PROXY 环境变量被设置为 1 或启用了 --use-env-proxy,全局代理将以 proxyEnv: process.env 构建,从而根据环境变量启用代理支持。通过在构建代理时传入 proxyEnv 选项,也可以创建具有代理支持的自定义代理。如果想要继承环境变量中的配置,该值可以设为 process.env,也可以是一个对象,用于覆盖环境变量的特定设置。
【When Node.js creates the global agent, if the NODE_USE_ENV_PROXY environment variable is
set to 1 or --use-env-proxy is enabled, the global agent will be constructed
with proxyEnv: process.env, enabling proxy support based on the environment variables.
Custom agents can also be created with proxy support by passing a
proxyEnv option when constructing the agent. The value can be process.env
if they just want to inherit the configuration from the environment variables,
or an object with specific setting overriding the environment.】
以下会检查 proxyEnv 的属性以配置代理支持。
【The following properties of the proxyEnv are checked to configure proxy
support.】
HTTP_PROXY或http_proxy:HTTP 请求的代理服务器 URL。如果两者都设置了,http_proxy优先。HTTPS_PROXY或https_proxy:用于 HTTPS 请求的代理服务器 URL。如果两者都设置了,https_proxy优先。NO_PROXY或no_proxy:以逗号分隔的要绕过代理的主机列表。如果两者都设置了,no_proxy优先。
如果请求是向 Unix 域套接字发送的,则代理设置将被忽略。
【If the request is made to a Unix domain socket, the proxy settings will be ignored.】
代理 URL 格式#>
【Proxy URL Format】
代理 URL 可以使用 HTTP 或 HTTPS 协议:
【Proxy URLs can use either HTTP or HTTPS protocols:】
- HTTP 代理:
http://proxy.example.com:8080 - HTTPS 代理:
https://proxy.example.com:8080 - 带认证的代理:
http://username:password@proxy.example.com:8080
NO_PROXY 格式#>
【NO_PROXY Format】
NO_PROXY 环境变量支持多种格式:
【The NO_PROXY environment variable supports several formats:】
*- 对所有主机绕过代理example.com- 精确主机名匹配.example.com- 域名后缀匹配(匹配sub.example.com)*.example.com- 通配符域名匹配192.168.1.100- 精确 IP 地址匹配192.168.1.1-192.168.1.100- IP 地址范围example.com:8080- 带有特定端口的主机名
多个条目应以逗号分隔。
【Multiple entries should be separated by commas.】
示例#>
【Example】
要启动一个 Node.js 进程,并为通过默认全局代理发送的所有请求启用代理支持,可以使用 NODE_USE_ENV_PROXY 环境变量:
【To start a Node.js process with proxy support enabled for all requests sent
through the default global agent, either use the NODE_USE_ENV_PROXY environment
variable:】
NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node client.js
或者使用 --use-env-proxy 参数。
【Or the --use-env-proxy flag.】
HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node --use-env-proxy client.js
要创建具有内置代理支持的自定义代理:
【To create a custom agent with built-in proxy support:】
const http = require('node:http');
// Creating a custom agent with custom proxy support.
const agent = new http.Agent({ proxyEnv: { HTTP_PROXY: 'http://proxy.example.com:8080' } });
http.request({
hostname: 'www.example.com',
port: 80,
path: '/',
agent,
}, (res) => {
// This request will be proxied through proxy.example.com:8080 using the HTTP protocol.
console.log(`STATUS: ${res.statusCode}`);
});
或者,以下方法也有效:
【Alternatively, the following also works:】
const http = require('node:http');
// Use lower-cased option name.
const agent1 = new http.Agent({ proxyEnv: { http_proxy: 'http://proxy.example.com:8080' } });
// Use values inherited from the environment variables, if the process is started with
// HTTP_PROXY=http://proxy.example.com:8080 this will use the proxy server specified
// in process.env.HTTP_PROXY.
const agent2 = new http.Agent({ proxyEnv: process.env });