- 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 域
- 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 单个可执行应用程序
Node.js v24.13.0 文档
- Node.js v24.13.0
-
目录
- HTTP/2
- 确定加密支持是否不可用
- 核心接口
- 服务器端示例
- 客户端示例
- 类:
Http2SessionHttp2Session和套接字- 事件:
'close' - 事件:
'connect' - 事件:
'错误' - 事件:
'frameError' - 事件:
'goaway' - 事件:
'localSettings' - 事件:
'ping' - 事件:
'remoteSettings' - 事件:
'stream' - 事件:
'timeout' http2session.alpnProtocolhttp2session.close([callback])http2session.closedhttp2session.connectinghttp2session.destroy([error][, code])http2session.destroyedhttp2session.encryptedhttp2session.goaway([code[, lastStreamID[, opaqueData]]])http2session.localSettingshttp2session.originSethttp2session.pendingSettingsAckhttp2session.ping([payload, ]callback)http2session.ref()http2session.remoteSettingshttp2session.setLocalWindowSize(windowSize)http2session.setTimeout(msecs, callback)http2session.sockethttp2session.statehttp2session.settings([settings][, callback])http2session.typehttp2session.unref()
- 类:
ServerHttp2Session - 类:
ClientHttp2Session - 类:
Http2StreamHttp2Stream生命周期- 事件:
'aborted' - 事件:
'close' - 事件:
'错误' - 事件:
'frameError' - 事件:
'ready' - 事件:
'timeout' - 事件:
'trailers' - 事件:
'wantTrailers' http2stream.abortedhttp2stream.bufferSizehttp2stream.close(code[, callback])http2stream.closedhttp2stream.destroyedhttp2stream.endAfterHeadershttp2stream.idhttp2stream.pendinghttp2stream.priority(options)http2stream.rstCodehttp2stream.sentHeadershttp2stream.sentInfoHeadershttp2stream.sentTrailershttp2stream.sessionhttp2stream.setTimeout(msecs, callback)http2stream.statehttp2stream.sendTrailers(headers)
- 类:
ClientHttp2Stream - 类:
ServerHttp2Stream - 类:
Http2Server - 类:
Http2SecureServer http2.createServer([options][, onRequestHandler])http2.createSecureServer(options[, onRequestHandler])http2.connect(authority[, options][, listener])http2.constantshttp2.getDefaultSettings()http2.getPackedSettings([settings])http2.getUnpackedSettings(buf)http2.performServerHandshake(socket[, options])http2.sensitiveHeaders- 标头对象
- 设置对象
- 错误处理
- 标头名称和值中的无效字符处理
- 在客户端推流
- 支持
CONNECT方法 - 扩展的
CONNECT协议
- 兼容性接口
- ALPN 协商
- 类:
http2.Http2ServerRequest- 事件:
'aborted' - 事件:
'close' request.abortedrequest.authorityrequest.completerequest.connectionrequest.destroy([error])request.headersrequest.httpVersionrequest.methodrequest.rawHeadersrequest.rawTrailersrequest.schemerequest.setTimeout(msecs, callback)request.socketrequest.streamrequest.trailersrequest.url
- 事件:
- 类:
http2.Http2ServerResponse- 事件:
'close' - 事件:
'finish' response.addTrailers(headers)response.appendHeader(name, value)response.connectionresponse.createPushResponse(headers, callback)response.end([data[, encoding]][, callback])response.finishedresponse.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.streamresponse.writableEndedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeEarlyHints(hints)response.writeHead(statusCode[, statusMessage][, headers])
- 事件:
- 收集 HTTP/2 性能指标
- 关于
:authority和host的说明
- HTTP/2
-
导航
- 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 域
- 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 单个可执行应用程序
- 其他版本
HTTP/2#>
源代码: lib/http2.js
node:http2 模块提供了 HTTP/2 协议的实现。
可以通过以下方式访问:
【The node:http2 module provides an implementation of the HTTP/2 protocol.
It can be accessed using:】
const http2 = require('node:http2');
确定加密支持是否不可用#>
【Determining if crypto support is unavailable】
Node.js 可以在不包含对 node:crypto 模块支持的情况下构建。在这种情况下,尝试从 node:http2 导入(import)或调用 require('node:http2') 将会抛出错误。
【It is possible for Node.js to be built without including support for the
node:crypto module. In such cases, attempting to import from node:http2 or
calling require('node:http2') will result in an error being thrown.】
使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:
【When using CommonJS, the error thrown can be caught using try/catch:】
let http2;
try {
http2 = require('node:http2');
} catch (err) {
console.error('http2 support is disabled!');
}
在使用词法 ESM import 关键字时,只有在尝试加载模块之前(例如使用预加载模块)注册了 process.on('uncaughtException') 的处理程序,才能捕获该错误。
【When using the lexical ESM import keyword, the error can only be
caught if a handler for process.on('uncaughtException') is registered
before any attempt to load the module is made (using, for instance,
a preload module).】
在使用 ESM 时,如果代码有可能在未启用加密支持的 Node.js 版本上运行,考虑使用 import() 函数替代词法 import 关键字:
【When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
import() function instead of the lexical import keyword:】
let http2;
try {
http2 = await import('node:http2');
} catch (err) {
console.error('http2 support is disabled!');
}
核心接口#>
【Core API】
核心 API 提供了一个低级接口,专门设计用于支持 HTTP/2 协议功能。它特别不旨在与现有的 HTTP/1 模块 API 兼容。然而,兼容性接口 是兼容的。
【The Core API provides a low-level interface designed specifically around support for HTTP/2 protocol features. It is specifically not designed for compatibility with the existing HTTP/1 module API. However, the Compatibility API is.】
http2 核心 API 在客户端和服务器端之间比 http API 对称得多。例如,大多数事件,如 'error'、'connect' 和 'stream',都可以由客户端代码或服务器端代码触发。
【The http2 Core API is much more symmetric between client and server than the
http API. For instance, most events, like 'error', 'connect' and
'stream', can be emitted either by client-side code or server-side code.】
服务器端示例#>
【Server-side example】
下面演示了一个使用 Core API 的简单 HTTP/2 服务器。由于目前没有已知浏览器支持 未加密的 HTTP/2,因此在与浏览器客户端通信时必须使用 http2.createSecureServer()。
【The following illustrates a simple HTTP/2 server using the Core API.
Since there are no browsers known that support
unencrypted HTTP/2, the use of
http2.createSecureServer() is necessary when communicating
with browser clients.】
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const server = createSecureServer({
key: readFileSync('localhost-privkey.pem'),
cert: readFileSync('localhost-cert.pem'),
});
server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);const http2 = require('node:http2');
const fs = require('node:fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem'),
});
server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
要为此示例生成证书和密钥,则运行:
【To generate the certificate and key for this example, run:】
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout localhost-privkey.pem -out localhost-cert.pem
客户端示例#>
【Client-side example】
以下说明了 HTTP/2 客户端:
【The following illustrates an HTTP/2 client:】
import { connect } from 'node:http2';
import { readFileSync } from 'node:fs';
const client = connect('https://localhost:8443', {
ca: readFileSync('localhost-cert.pem'),
});
client.on('error', (err) => console.error(err));
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
for (const name in headers) {
console.log(`${name}: ${headers[name]}`);
}
});
req.setEncoding('utf8');
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
console.log(`\n${data}`);
client.close();
});
req.end();const http2 = require('node:http2');
const fs = require('node:fs');
const client = http2.connect('https://localhost:8443', {
ca: fs.readFileSync('localhost-cert.pem'),
});
client.on('error', (err) => console.error(err));
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
for (const name in headers) {
console.log(`${name}: ${headers[name]}`);
}
});
req.setEncoding('utf8');
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
console.log(`\n${data}`);
client.close();
});
req.end();
类:Http2Session#>
【Class: Http2Session】
http2.Http2Session 类的实例表示 HTTP/2 客户端和服务器之间的活动通信会话。该类的实例 不 应由用户代码直接构造。
【Instances of the http2.Http2Session class represent an active communications
session between an HTTP/2 client and server. Instances of this class are not
intended to be constructed directly by user code.】
每个 Http2Session 实例的行为可能会略有不同,这取决于它是作为服务器还是客户端运行。可以使用 http2session.type 属性来确定 Http2Session 的运行模式。在服务器端,用户代码很少需要直接操作 Http2Session 对象,大多数操作通常是通过与 Http2Server 或 Http2Stream 对象的交互来完成的。
【Each Http2Session instance will exhibit slightly different behaviors
depending on whether it is operating as a server or a client. The
http2session.type property can be used to determine the mode in which an
Http2Session is operating. On the server side, user code should rarely
have occasion to work with the Http2Session object directly, with most
actions typically taken through interactions with either the Http2Server or
Http2Stream objects.】
用户代码不会直接创建 Http2Session 实例。服务端的 Http2Session 实例是在接收到新的 HTTP/2 连接时由 Http2Server 实例创建的。客户端的 Http2Session 实例是通过使用 http2.connect() 方法创建的。
【User code will not create Http2Session instances directly. Server-side
Http2Session instances are created by the Http2Server instance when a
new HTTP/2 connection is received. Client-side Http2Session instances are
created using the http2.connect() method.】
Http2Session 和套接字#>
【Http2Session and sockets】
每个 Http2Session 实例在创建时都会与一个 net.Socket 或 tls.TLSSocket 关联。当 Socket 或 Http2Session 被销毁时,二者都会被销毁。
【Every Http2Session instance is associated with exactly one net.Socket or
tls.TLSSocket when it is created. When either the Socket or the
Http2Session are destroyed, both will be destroyed.】
由于 HTTP/2 协议施加了特定的序列化和处理要求,不建议用户代码从绑定到 Http2Session 的 Socket 实例读取数据或向其写入数据。这样做可能会使 HTTP/2 会话处于不确定状态,从而导致会话和套接字无法使用。
【Because of the specific serialization and processing requirements imposed
by the HTTP/2 protocol, it is not recommended for user code to read data from
or write data to a Socket instance bound to a Http2Session. Doing so can
put the HTTP/2 session into an indeterminate state causing the session and
the socket to become unusable.】
一旦 Socket 已绑定到 Http2Session,用户代码应仅依赖 Http2Session 的 API。
【Once a Socket has been bound to an Http2Session, user code should rely
solely on the API of the Http2Session.】
事件:'close'#>
【Event: 'close'】
'close' 事件在 Http2Session 被销毁后触发。它的监听器不期望任何参数。
【The 'close' event is emitted once the Http2Session has been destroyed. Its
listener does not expect any arguments.】
事件:'connect'#>
【Event: 'connect'】
session<Http2Session>socket<net.Socket>
一旦 Http2Session 成功连接到远程节点并可以开始通信,就会触发 'connect' 事件。
【The 'connect' event is emitted once the Http2Session has been successfully
connected to the remote peer and communication may begin.】
用户代码通常不会直接监听此事件。
【User code will typically not listen for this event directly.】
事件:'错误'#>
【Event: 'error'】
error<Error>
'error' 事件在处理 Http2Session 时发生错误时被触发。
【The 'error' event is emitted when an error occurs during the processing of
an Http2Session.】
事件:'frameError'#>
【Event: 'frameError'】
'frameError' 事件在尝试在会话中发送帧时发生错误时触发。如果无法发送的帧与特定的 Http2Stream 相关联,则会尝试在 Http2Stream 上触发 'frameError' 事件。
【The 'frameError' event is emitted when an error occurs while attempting to
send a frame on the session. If the frame that could not be sent is associated
with a specific Http2Stream, an attempt to emit a 'frameError' event on the
Http2Stream is made.】
如果 'frameError' 事件与某个流相关联,该流将在 'frameError' 事件之后立即被关闭和销毁。如果事件与任何流无关,Http2Session 将在 'frameError' 事件之后立即关闭。
【If the 'frameError' event is associated with a stream, the stream will be
closed and destroyed immediately following the 'frameError' event. If the
event is not associated with a stream, the Http2Session will be shut down
immediately following the 'frameError' event.】
事件:'goaway'#>
【Event: 'goaway'】
errorCode<number>GOAWAY帧中指定的 HTTP/2 错误代码。lastStreamID<number> 远程对等方成功处理的最后一个流的ID(如果未指定ID,则为0)。opaqueData<Buffer> 如果在GOAWAY帧中包含了额外的不透明数据,将会传入一个包含这些数据的Buffer实例。
当接收到 GOAWAY 帧时,会触发 'goaway' 事件。
【The 'goaway' event is emitted when a GOAWAY frame is received.】
Http2Session 实例将在 'goaway' 事件触发时自动关闭。
【The Http2Session instance will be shut down automatically when the 'goaway'
event is emitted.】
事件:'localSettings'#>
【Event: 'localSettings'】
settingsHTTP/2 设置对象 接收到的SETTINGS帧的副本。
当接收到确认的 SETTINGS 帧时,会触发 'localSettings' 事件。
【The 'localSettings' event is emitted when an acknowledgment SETTINGS frame
has been received.】
使用 http2session.settings() 提交新设置时,修改后的设置在 'localSettings' 事件触发之前不会生效。
【When using http2session.settings() to submit new settings, the modified
settings do not take effect until the 'localSettings' event is emitted.】
session.settings({ enablePush: false });
session.on('localSettings', (settings) => {
/* Use the new settings */
});
事件:'ping'#>
【Event: 'ping'】
payload<Buffer>PING帧的 8 字节负载
每当从连接的对等方接收到 PING 帧时,就会触发 'ping' 事件。
【The 'ping' event is emitted whenever a PING frame is received from the
connected peer.】
事件:'remoteSettings'#>
【Event: 'remoteSettings'】
settingsHTTP/2 设置对象 接收到的SETTINGS帧的副本。
当从连接的对等方接收到新的 SETTINGS 帧时,会触发 'remoteSettings' 事件。
【The 'remoteSettings' event is emitted when a new SETTINGS frame is received
from the connected peer.】
session.on('remoteSettings', (settings) => {
/* Use the new settings */
});
事件:'stream'#>
【Event: 'stream'】
stream<Http2Stream> 对流的引用headersHTTP/2 头对象 一个描述头信息的对象flags<number> 相关的数字标志rawHeadersHTTP/2 原始头 一个包含原始头的数组
当创建新的 Http2Stream 时,会触发 'stream' 事件。
【The 'stream' event is emitted when a new Http2Stream is created.】
session.on('stream', (stream, headers, flags) => {
const method = headers[':method'];
const path = headers[':path'];
// ...
stream.respond({
':status': 200,
'content-type': 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
});
在服务器端,用户代码通常不会直接监听此事件,而是会为 http2.createServer() 和 http2.createSecureServer() 返回的 net.Server 或 tls.Server 实例发出的 'stream' 事件注册一个处理程序,如下面的示例所示:
【On the server side, user code will typically not listen for this event directly,
and would instead register a handler for the 'stream' event emitted by the
net.Server or tls.Server instances returned by http2.createServer() and
http2.createSecureServer(), respectively, as in the example below:】
import { createServer } from 'node:http2';
// Create an unencrypted HTTP/2 server
const server = createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.on('error', (error) => console.error(error));
stream.end('<h1>Hello World</h1>');
});
server.listen(8000);const http2 = require('node:http2');
// Create an unencrypted HTTP/2 server
const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.on('error', (error) => console.error(error));
stream.end('<h1>Hello World</h1>');
});
server.listen(8000);
尽管 HTTP/2 流和网络套接字不是一一对应的,网络错误会破坏每个单独的流,并且必须在流级别处理,如上所示。
【Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above.】
事件:'timeout'#>
【Event: 'timeout'】
在使用 http2session.setTimeout() 方法为此 Http2Session 设置超时时间后,如果在配置的毫秒数内 Http2Session 没有任何活动,就会触发 'timeout' 事件。它的监听器不需要任何参数。
【After the http2session.setTimeout() method is used to set the timeout period
for this Http2Session, the 'timeout' event is emitted if there is no
activity on the Http2Session after the configured number of milliseconds.
Its listener does not expect any arguments.】
session.setTimeout(2000);
session.on('timeout', () => { /* .. */ });
http2session.alpnProtocol#>
- 类型:<string> | <undefined>
如果 Http2Session 尚未连接到套接字,值将为 undefined;如果 Http2Session 未连接到 TLSSocket,值将为 h2c;或者将返回已连接 TLSSocket 自身的 alpnProtocol 属性的值。
【Value will be undefined if the Http2Session is not yet connected to a
socket, h2c if the Http2Session is not connected to a TLSSocket, or
will return the value of the connected TLSSocket's own alpnProtocol
property.】
http2session.close([callback])#>
callback<Function>
优雅地关闭 Http2Session,允许现有的流自行完成,并阻止创建新的 Http2Stream 实例。关闭后,如果没有打开的 Http2Stream 实例,可能会调用 http2session.destroy()。
【Gracefully closes the Http2Session, allowing any existing streams to
complete on their own and preventing new Http2Stream instances from being
created. Once closed, http2session.destroy() might be called if there
are no open Http2Stream instances.】
如果指定,callback 函数将被注册为 'close' 事件的处理程序。
【If specified, the callback function is registered as a handler for the
'close' event.】
http2session.closed#>
- 类型:<boolean>
如果该 Http2Session 实例已关闭,则为 true,否则为 false。
【Will be true if this Http2Session instance has been closed, otherwise
false.】
http2session.connecting#>
- 类型:<boolean>
如果此 Http2Session 实例仍在连接中,则为 true,在触发 connect 事件和/或调用 http2.connect 回调之前,会被设置为 false。
【Will be true if this Http2Session instance is still connecting, will be set
to false before emitting connect event and/or calling the http2.connect
callback.】
http2session.destroy([error][, code])#>
error<Error> 如果Http2Session因错误而被销毁,则返回一个Error对象。code<number> 在最终GOAWAY帧中发送的 HTTP/2 错误代码。如果未指定,且error不为未定义,则默认为INTERNAL_ERROR,否则默认为NO_ERROR。
立即终止 Http2Session 及相关的 net.Socket 或 tls.TLSSocket。
【Immediately terminates the Http2Session and the associated net.Socket or
tls.TLSSocket.】
一旦被销毁,Http2Session 会触发 'close' 事件。如果 error 不为 undefined,则 'error' 事件会在 'close' 事件之前立即触发。
【Once destroyed, the Http2Session will emit the 'close' event. If error
is not undefined, an 'error' event will be emitted immediately before the
'close' event.】
如果有任何仍然打开的与 Http2Session 关联的 Http2Streams,它们也将被销毁。
【If there are any remaining open Http2Streams associated with the
Http2Session, those will also be destroyed.】
http2session.destroyed#>
- 类型:<boolean>
如果此 Http2Session 实例已被销毁且不应再使用,则为 true,否则为 false。
【Will be true if this Http2Session instance has been destroyed and must no
longer be used, otherwise false.】
http2session.encrypted#>
- 类型: <boolean> | <undefined>
如果 Http2Session 会话套接字尚未连接,则值为 undefined;如果 Http2Session 已通过 TLSSocket 连接,则值为 true;如果 Http2Session 连接到其他类型的套接字或流,则值为 false。
【Value is undefined if the Http2Session session socket has not yet been
connected, true if the Http2Session is connected with a TLSSocket,
and false if the Http2Session is connected to any other kind of socket
or stream.】
http2session.goaway([code[, lastStreamID[, opaqueData]]])#>
code<number> 一个 HTTP/2 错误代码lastStreamID<number> 最后处理的Http2Stream的数字 IDopaqueData<Buffer> | <TypedArray> | <DataView> 一个TypedArray或DataView实例,包含将在GOAWAY帧中携带的附加数据。
向连接的对等方发送 GOAWAY 帧,_不_关闭 Http2Session。
【Transmits a GOAWAY frame to the connected peer without shutting down the
Http2Session.】
http2session.localSettings#>
- 类型:HTTP/2 设置对象
一个无原型对象,描述此 Http2Session 当前的本地设置。本地设置是针对 此 Http2Session 实例的本地设置。
【A prototype-less object describing the current local settings of this
Http2Session. The local settings are local to this Http2Session instance.】
http2session.originSet#>
- 类型: <string[]>
如果 Http2Session 已连接到 TLSSocket,则 originSet 属性将返回一个 Array,其中包含 Http2Session 可能被认为具有权威性的源。
【If the Http2Session is connected to a TLSSocket, the originSet property
will return an Array of origins for which the Http2Session may be
considered authoritative.】
originSet 属性仅在使用安全的 TLS 连接时可用。
【The originSet property is only available when using a secure TLS connection.】
http2session.pendingSettingsAck#>
- 类型:<boolean>
指示 Http2Session 当前是否正在等待已发送的 SETTINGS 帧的确认。调用 http2session.settings() 方法后,该值将为 true。一旦所有已发送的 SETTINGS 帧都被确认,该值将为 false。
【Indicates whether the Http2Session is currently waiting for acknowledgment of
a sent SETTINGS frame. Will be true after calling the
http2session.settings() method. Will be false once all sent SETTINGS
frames have been acknowledged.】
http2session.ping([payload, ]callback)#>
payload<Buffer> | <TypedArray> | <DataView> 可选的 ping 负载。callback<Function>- 返回:<boolean>
向已连接的 HTTP/2 对等方发送 PING 帧。必须提供一个 callback 函数。如果 PING 发送成功,该方法将返回 true,否则返回 false。
【Sends a PING frame to the connected HTTP/2 peer. A callback function must
be provided. The method will return true if the PING was sent, false
otherwise.】
maxOutstandingPings 配置选项决定了未确认 ping 的最大数量。默认最大值为 10。
【The maximum number of outstanding (unacknowledged) pings is determined by the
maxOutstandingPings configuration option. The default maximum is 10.】
如果提供,payload 必须是一个包含 8 字节数据的 Buffer、TypedArray 或 DataView,这些数据将随 PING 发送,并在 ping 确认时返回。
【If provided, the payload must be a Buffer, TypedArray, or DataView
containing 8 bytes of data that will be transmitted with the PING and
returned with the ping acknowledgment.】
回调函数将接收三个参数:一个错误参数,如果 PING 被成功确认,该参数将为 null;一个 duration 参数,报告从发送 ping 到收到确认所经过的毫秒数;以及一个包含 8 字节 PING 数据的 Buffer。
【The callback will be invoked with three arguments: an error argument that will
be null if the PING was successfully acknowledged, a duration argument
that reports the number of milliseconds elapsed since the ping was sent and the
acknowledgment was received, and a Buffer containing the 8-byte PING
payload.】
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
if (!err) {
console.log(`Ping acknowledged in ${duration} milliseconds`);
console.log(`With payload '${payload.toString()}'`);
}
});
如果未指定 payload 参数,默认的负载将是标记 PING 持续时间开始的 64 位时间戳(小端序)。
【If the payload argument is not specified, the default payload will be the
64-bit timestamp (little endian) marking the start of the PING duration.】
http2session.ref()#>
在此 Http2Session 实例的底层 net.Socket 上调用 ref()。
【Calls ref() on this Http2Session
instance's underlying net.Socket.】
http2session.remoteSettings#>
- 类型:HTTP/2 设置对象
一个无原型对象,描述此 Http2Session 的当前远程设置。远程设置由已连接的 HTTP/2 对端设置。
【A prototype-less object describing the current remote settings of this
Http2Session. The remote settings are set by the connected HTTP/2 peer.】
http2session.setLocalWindowSize(windowSize)#>
windowSize<number>
设置本地端点的窗口大小。
windowSize 是要设置的总窗口大小,而不是增量。
【Sets the local endpoint's window size.
The windowSize is the total window size to set, not
the delta.】
import { createServer } from 'node:http2';
const server = createServer();
const expectedWindowSize = 2 ** 20;
server.on('session', (session) => {
// Set local window size to be 2 ** 20
session.setLocalWindowSize(expectedWindowSize);
});const http2 = require('node:http2');
const server = http2.createServer();
const expectedWindowSize = 2 ** 20;
server.on('session', (session) => {
// Set local window size to be 2 ** 20
session.setLocalWindowSize(expectedWindowSize);
});
对于 http2 客户端,正确的事件是 'connect' 或 'remoteSettings'。
【For http2 clients the proper event is either 'connect' or 'remoteSettings'.】
http2session.setTimeout(msecs, callback)#>
msecs<number>callback<Function>
用于设置一个回调函数,当 Http2Session 在 msecs 毫秒后没有活动时调用。给定的 callback 会被注册为 'timeout' 事件的监听器。
【Used to set a callback function that is called when there is no activity on
the Http2Session after msecs milliseconds. The given callback is
registered as a listener on the 'timeout' event.】
http2session.socket#>
- 类型: <net.Socket> | <tls.TLSSocket>
返回一个 Proxy 对象,该对象表现得像一个 net.Socket(或 tls.TLSSocket),但限制可用方法为在 HTTP/2 中安全使用的方法。
【Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but
limits available methods to ones safe to use with HTTP/2.】
destroy、emit、end、pause、read、resume 和 write 将抛出代码为 ERR_HTTP2_NO_SOCKET_MANIPULATION 的错误。更多信息请参见 Http2Session 和套接字。
setTimeout 方法将被调用于此 Http2Session 上。
所有其他交互将直接路由到套接字。
【All other interactions will be routed directly to the socket.】
http2session.state#>
提供有关当前 Http2Session 状态的各种信息。
【Provides miscellaneous information about the current state of the
Http2Session.】
- 类型: <Object>
effectiveLocalWindowSize<number> 当前Http2Session的本地(接收)流量控制窗口大小。effectiveRecvDataLength<number> 自上次流量控制WINDOW_UPDATE以来已接收的字节数。nextStreamID<number> 下次由此Http2Session创建新的Http2Stream时将使用的数字标识符。localWindowSize<number> 远程节点在收到WINDOW_UPDATE前可以发送的字节数。lastProcStreamID<number> 最近接收到HEADERS或DATA帧的Http2Stream的数字 ID。remoteWindowSize<number> 此Http2Session在接收到WINDOW_UPDATE之前可以发送的字节数。outboundQueueSize<number> 当前在此Http2Session的出站队列中的帧数。deflateDynamicTableSize<number> 出站头部压缩状态表当前的字节大小。inflateDynamicTableSize<number> 当前入站头部压缩状态表的字节大小。
描述此 Http2Session 当前状态的对象。
【An object describing the current status of this Http2Session.】
http2session.settings([settings][, callback])#>
settingsHTTP/2 设置对象callback<Function> 会话连接后调用的回调,如果会话已连接,则会立即调用。
更新此 Http2Session 的当前本地设置,并向已连接的 HTTP/2 对等端发送一个新的 SETTINGS 帧。
【Updates the current local settings for this Http2Session and sends a new
SETTINGS frame to the connected HTTP/2 peer.】
一旦被调用,当会话等待远程端确认新的设置时,http2session.pendingSettingsAck 属性将为 true。
【Once called, the http2session.pendingSettingsAck property will be true
while the session is waiting for the remote peer to acknowledge the new
settings.】
新的设置在接收到 SETTINGS 确认并触发 'localSettings' 事件之前不会生效。在确认仍在等待时,可以发送多个 SETTINGS 帧。
【The new settings will not become effective until the SETTINGS acknowledgment
is received and the 'localSettings' event is emitted. It is possible to send
multiple SETTINGS frames while acknowledgment is still pending.】
http2session.type#>
- 类型:<number>
http2session.type 如果这个 Http2Session 实例是服务器,将等于 http2.constants.NGHTTP2_SESSION_SERVER;如果实例是客户端,则等于 http2.constants.NGHTTP2_SESSION_CLIENT。
【The http2session.type will be equal to
http2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a
server, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a
client.】
http2session.unref()#>
在此 Http2Session 实例的底层 net.Socket 上调用 unref()。
【Calls unref() on this Http2Session
instance's underlying net.Socket.】
类:ServerHttp2Session#>
【Class: ServerHttp2Session】
serverhttp2session.altsvc(alt, originOrStream)#>
alt<string> 对 RFC 7838 定义的替代服务配置的描述。originOrStream<number> | <string> | <URL> | <Object> 可以是指定源的 URL 字符串(或具有origin属性的Object),也可以是活动Http2Stream的数字标识符,该标识符由http2stream.id属性提供。
向已连接的客户端提交一个 ALTSVC 帧(由 RFC 7838 定义)。
【Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.】
import { createServer } from 'node:http2';
const server = createServer();
server.on('session', (session) => {
// Set altsvc for origin https://example.org:80
session.altsvc('h2=":8000"', 'https://example.org:80');
});
server.on('stream', (stream) => {
// Set altsvc for a specific stream
stream.session.altsvc('h2=":8000"', stream.id);
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('session', (session) => {
// Set altsvc for origin https://example.org:80
session.altsvc('h2=":8000"', 'https://example.org:80');
});
server.on('stream', (stream) => {
// Set altsvc for a specific stream
stream.session.altsvc('h2=":8000"', stream.id);
});
发送带有特定流 ID 的 ALTSVC 帧表示备用服务与给定 Http2Stream 的源相关联。
【Sending an ALTSVC frame with a specific stream ID indicates that the alternate
service is associated with the origin of the given Http2Stream.】
alt 和 origin 字符串 必须 只包含 ASCII 字节,并且严格按照 ASCII 字节序列进行解释。特殊值 'clear' 可以用于清除之前为某个域设置的任何备用服务。
【The alt and origin string must contain only ASCII bytes and are
strictly interpreted as a sequence of ASCII bytes. The special value 'clear'
may be passed to clear any previously set alternative service for a given
domain.】
当为 originOrStream 参数传递一个字符串时,该字符串将被解析为 URL,并从中获取源。例如,HTTP URL 'https://example.org/foo/bar' 的源是 ASCII 字符串 'https://example.org'。如果给定的字符串无法被解析为 URL,或无法推导出有效的源,将会抛出错误。
【When a string is passed for the originOrStream argument, it will be parsed as
a URL and the origin will be derived. For instance, the origin for the
HTTP URL 'https://example.org/foo/bar' is the ASCII string
'https://example.org'. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.】
一个 URL 对象,或者任何具有 origin 属性的对象,都可以作为 originOrStream 传入,此时将使用 origin 属性的值。origin 属性的值必须是正确序列化的 ASCII 源。
【A URL object, or any object with an origin property, may be passed as
originOrStream, in which case the value of the origin property will be
used. The value of the origin property must be a properly serialized
ASCII origin.】
指定替代服务#>
【Specifying alternative services】
alt 参数的格式由 RFC 7838 严格规定,为一个 ASCII 字符串,包含与特定主机和端口相关的“备用”协议的逗号分隔列表。
【The format of the alt parameter is strictly defined by RFC 7838 as an
ASCII string containing a comma-delimited list of "alternative" protocols
associated with a specific host and port.】
例如,值 'h2="example.org:81"' 表示 HTTP/2 协议可在主机 'example.org' 的 TCP/IP 端口 81 上使用。主机和端口必须包含在引号(")字符内。
【For example, the value 'h2="example.org:81"' indicates that the HTTP/2
protocol is available on the host 'example.org' on TCP/IP port 81. The
host and port must be contained within the quote (") characters.】
可以指定多个替代项,例如:'h2="example.org:81", h2=":82"'。
【Multiple alternatives may be specified, for instance: 'h2="example.org:81", h2=":82"'.】
协议标识符(示例中的 'h2')可以是任何有效的 ALPN 协议标识。
【The protocol identifier ('h2' in the examples) may be any valid
ALPN Protocol ID.】
这些值的语法不会被 Node.js 实现验证,会按照用户提供的或从对端接收到的原样传递。
【The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer.】
serverhttp2session.origin(...origins)#>
向已连接的客户端提交一个 ORIGIN 帧(如 RFC 8336 定义),以通告服务器能够提供权威响应的一组源。
【Submits an ORIGIN frame (as defined by RFC 8336) to the connected client
to advertise the set of origins for which the server is capable of providing
authoritative responses.】
import { createSecureServer } from 'node:http2';
const options = getSecureOptionsSomehow();
const server = createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});
server.on('session', (session) => {
session.origin('https://example.com', 'https://example.org');
});const http2 = require('node:http2');
const options = getSecureOptionsSomehow();
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});
server.on('session', (session) => {
session.origin('https://example.com', 'https://example.org');
});
当一个字符串作为 origin 传入时,它会被解析为一个 URL,并从中得出原点。例如,HTTP URL 'https://example.org/foo/bar' 的原点是 ASCII 字符串 'https://example.org'。如果给定的字符串无法解析为 URL,或者无法得出有效的原点,将会抛出错误。
【When a string is passed as an origin, it will be parsed as a URL and the
origin will be derived. For instance, the origin for the HTTP URL
'https://example.org/foo/bar' is the ASCII string
'https://example.org'. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.】
可以将 URL 对象或任何具有 origin 属性的对象作为 origin 传入,这种情况下将使用 origin 属性的值。origin 属性的值必须是正确序列化的 ASCII 来源。
【A URL object, or any object with an origin property, may be passed as
an origin, in which case the value of the origin property will be
used. The value of the origin property must be a properly serialized
ASCII origin.】
或者,在使用 http2.createSecureServer() 方法创建新的 HTTP/2 服务器时,可以使用 origins 选项:
【Alternatively, the origins option may be used when creating a new HTTP/2
server using the http2.createSecureServer() method:】
import { createSecureServer } from 'node:http2';
const options = getSecureOptionsSomehow();
options.origins = ['https://example.com', 'https://example.org'];
const server = createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});const http2 = require('node:http2');
const options = getSecureOptionsSomehow();
options.origins = ['https://example.com', 'https://example.org'];
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});
类:ClientHttp2Session#>
【Class: ClientHttp2Session】
事件:'altsvc'#>
【Event: 'altsvc'】
每当客户端接收到 ALTSVC 帧时,会触发 'altsvc' 事件。该事件会携带 ALTSVC 值、源(origin)和流 ID。如果 ALTSVC 帧中未提供 origin,则 origin 将为空字符串。
【The 'altsvc' event is emitted whenever an ALTSVC frame is received by
the client. The event is emitted with the ALTSVC value, origin, and stream
ID. If no origin is provided in the ALTSVC frame, origin will
be an empty string.】
import { connect } from 'node:http2';
const client = connect('https://example.org');
client.on('altsvc', (alt, origin, streamId) => {
console.log(alt);
console.log(origin);
console.log(streamId);
});const http2 = require('node:http2');
const client = http2.connect('https://example.org');
client.on('altsvc', (alt, origin, streamId) => {
console.log(alt);
console.log(origin);
console.log(streamId);
});
事件:'origin'#>
【Event: 'origin'】
origins字符串数组
每当客户端接收到 ORIGIN 帧时,就会触发 'origin' 事件。该事件会携带一个 origin 字符串数组。http2session.originSet 将会更新以包含接收到的原点。
【The 'origin' event is emitted whenever an ORIGIN frame is received by
the client. The event is emitted with an array of origin strings. The
http2session.originSet will be updated to include the received
origins.】
import { connect } from 'node:http2';
const client = connect('https://example.org');
client.on('origin', (origins) => {
for (let n = 0; n < origins.length; n++)
console.log(origins[n]);
});const http2 = require('node:http2');
const client = http2.connect('https://example.org');
client.on('origin', (origins) => {
for (let n = 0; n < origins.length; n++)
console.log(origins[n]);
});
只有在使用安全的 TLS 连接时才会触发 'origin' 事件。
【The 'origin' event is only emitted when using a secure TLS connection.】
clienthttp2session.request(headers[, options])#>
headersHTTP/2 请求头对象|HTTP/2 原始请求头options<Object>endStream<boolean>true如果Http2Stream的可写端应该最初关闭,例如在发送不应预期有有效负载主体的GET请求时。exclusive<boolean> 当值为true且parent指定了一个父流时,创建的流将成为父流的唯一直接依赖,所有其他现有的依赖将成为新创建流的依赖。 默认值:false。parent<number> 指定新创建的流所依赖的流的数字标识符。waitForTrailers<boolean> 当设置为true时,Http2Stream会在最后一个DATA帧发送后触发'wantTrailers'事件。signal<AbortSignal> 一个可以用来中止正在进行的请求的 AbortSignal。
- 返回:<ClientHttp2Stream>
仅适用于 HTTP/2 客户端的 Http2Session 实例,http2session.request() 会创建并返回一个 Http2Stream 实例,可用于向已连接的服务器发送 HTTP/2 请求。
【For HTTP/2 Client Http2Session instances only, the http2session.request()
creates and returns an Http2Stream instance that can be used to send an
HTTP/2 request to the connected server.】
当 ClientHttp2Session 刚创建时,套接字可能尚未连接。如果在此期间调用 clienthttp2session.request(),实际的请求将被延迟,直到套接字准备好。如果在实际请求执行之前 session 被关闭,将抛出 ERR_HTTP2_GOAWAY_SESSION 错误。
【When a ClientHttp2Session is first created, the socket may not yet be
connected. if clienthttp2session.request() is called during this time, the
actual request will be deferred until the socket is ready to go.
If the session is closed before the actual request be executed, an
ERR_HTTP2_GOAWAY_SESSION is thrown.】
仅当 http2session.type 等于 http2.constants.NGHTTP2_SESSION_CLIENT 时,此方法才可用。
【This method is only available if http2session.type is equal to
http2.constants.NGHTTP2_SESSION_CLIENT.】
import { connect, constants } from 'node:http2';
const clientSession = connect('https://localhost:1234');
const {
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
} = constants;
const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
req.on('response', (headers) => {
console.log(headers[HTTP2_HEADER_STATUS]);
req.on('data', (chunk) => { /* .. */ });
req.on('end', () => { /* .. */ });
});const http2 = require('node:http2');
const clientSession = http2.connect('https://localhost:1234');
const {
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
} = http2.constants;
const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
req.on('response', (headers) => {
console.log(headers[HTTP2_HEADER_STATUS]);
req.on('data', (chunk) => { /* .. */ });
req.on('end', () => { /* .. */ });
});
当设置了 options.waitForTrailers 选项时,'wantTrailers' 事件会在最后一块要发送的有效负载数据排队后立即触发。然后可以调用 http2stream.sendTrailers() 方法向对端发送尾部头信息。
【When the options.waitForTrailers option is set, the 'wantTrailers' event
is emitted immediately after queuing the last chunk of payload data to be sent.
The http2stream.sendTrailers() method can then be called to send trailing
headers to the peer.】
当设置 options.waitForTrailers 时,Http2Stream 在发送最后一个 DATA 帧后不会自动关闭。用户代码必须调用 http2stream.sendTrailers() 或 http2stream.close() 来关闭 Http2Stream。
【When options.waitForTrailers is set, the Http2Stream will not automatically
close when the final DATA frame is transmitted. User code must call either
http2stream.sendTrailers() or http2stream.close() to close the
Http2Stream.】
当使用 AbortSignal 设置 options.signal,然后调用相应 AbortController 的 abort 时,请求将发出带有 AbortError 错误的 'error' 事件。
【When options.signal is set with an AbortSignal and then abort on the
corresponding AbortController is called, the request will emit an 'error'
event with an AbortError error.】
:method 和 :path 伪头未在 headers 中指定,它们分别默认为:
【The :method and :path pseudo-headers are not specified within headers,
they respectively default to:】
:method='GET':path=/
类:Http2Stream#>
【Class: Http2Stream】
- 扩展自: <stream.Duplex>
Http2Stream 类的每个实例表示通过 Http2Session 实例进行的双向 HTTP/2 通信流。任何单个 Http2Session 在其生命周期内最多可以拥有 231-1 个 Http2Stream 实例。
用户代码不会直接构造 Http2Stream 实例。相反,这些实例是通过 Http2Session 实例创建、管理并提供给用户代码的。在服务器端,Http2Stream 实例要么是响应传入的 HTTP 请求创建的(并通过 'stream' 事件交给用户代码),要么是响应调用 http2stream.pushStream() 方法创建的。在客户端,当调用 http2session.request() 方法或者响应传入的 'push' 事件时,会创建并返回 Http2Stream 实例。
【User code will not construct Http2Stream instances directly. Rather, these
are created, managed, and provided to user code through the Http2Session
instance. On the server, Http2Stream instances are created either in response
to an incoming HTTP request (and handed off to user code via the 'stream'
event), or in response to a call to the http2stream.pushStream() method.
On the client, Http2Stream instances are created and returned when either the
http2session.request() method is called, or in response to an incoming
'push' event.】
Http2Stream 类是 ServerHttp2Stream 和 ClientHttp2Stream 类的基类,每个类分别专门用于服务器端或客户端。
【The Http2Stream class is a base for the ServerHttp2Stream and
ClientHttp2Stream classes, each of which is used specifically by either
the Server or Client side, respectively.】
所有 Http2Stream 实例都是 Duplex 流。Duplex 的 Writable 端用于向已连接的对等方发送数据,而 Readable 端用于接收已连接对等方发送的数据。
【All Http2Stream instances are Duplex streams. The Writable side of the
Duplex is used to send data to the connected peer, while the Readable side
is used to receive data sent by the connected peer.】
Http2Stream 的默认文本字符编码是 UTF-8。使用 Http2Stream 发送文本时,请使用 'content-type' 头来设置字符编码。
【The default text character encoding for an Http2Stream is UTF-8. When using an
Http2Stream to send text, use the 'content-type' header to set the character
encoding.】
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
Http2Stream 生命周期#>
【Http2Stream Lifecycle】
创建#>
【Creation】
在服务器端,ServerHttp2Stream 的实例会在以下情况下创建:
【On the server side, instances of ServerHttp2Stream are created either
when:】
- 接收到一个具有先前未使用的流 ID 的新的 HTTP/2
HEADERS帧; http2stream.pushStream()方法被调用。
在客户端,当调用 http2session.request() 方法时,会创建 ClientHttp2Stream 的实例。
【On the client side, instances of ClientHttp2Stream are created when the
http2session.request() method is called.】
在客户端,由 http2session.request() 返回的 Http2Stream 实例如果父 Http2Session 尚未完全建立,可能无法立即使用。在这种情况下,对 Http2Stream 调用的操作会被缓冲,直到 'ready' 事件被触发。用户代码通常很少需要,甚至几乎不需要直接处理 'ready' 事件。Http2Stream 的就绪状态可以通过检查 http2stream.id 的值来确定。如果该值为 undefined,则表示该流尚未准备好使用。
【On the client, the Http2Stream instance returned by http2session.request()
may not be immediately ready for use if the parent Http2Session has not yet
been fully established. In such cases, operations called on the Http2Stream
will be buffered until the 'ready' event is emitted. User code should rarely,
if ever, need to handle the 'ready' event directly. The ready status of an
Http2Stream can be determined by checking the value of http2stream.id. If
the value is undefined, the stream is not yet ready for use.】
解构#>
【Destruction】
所有 Http2Stream 实例都会在以下情况被销毁:
【All Http2Stream instances are destroyed either when:】
- 已由连接的对等方接收到该流的
RST_STREAM帧,并且(仅对于客户端流)已读取了挂起的数据。 http2stream.close()方法被调用,并且(仅对于客户端流)挂起的数据已被读取。http2stream.destroy()或http2session.destroy()方法被调用。
当一个 Http2Stream 实例被销毁时,将尝试向已连接的对等端发送一个 RST_STREAM 帧。
【When an Http2Stream instance is destroyed, an attempt will be made to send an
RST_STREAM frame to the connected peer.】
当 Http2Stream 实例被销毁时,将会触发 'close' 事件。由于 Http2Stream 是 stream.Duplex 的一个实例,如果流数据当前正在流动,还会触发 'end' 事件。如果 http2stream.destroy() 被调用时传入了一个 Error 作为第一个参数,也可能会触发 'error' 事件。
【When the Http2Stream instance is destroyed, the 'close' event will
be emitted. Because Http2Stream is an instance of stream.Duplex, the
'end' event will also be emitted if the stream data is currently flowing.
The 'error' event may also be emitted if http2stream.destroy() was called
with an Error passed as the first argument.】
Http2Stream 被销毁后,http2stream.destroyed 属性将为 true,http2stream.rstCode 属性将指定 RST_STREAM 错误代码。一旦 Http2Stream 实例被销毁,就无法再使用。
【After the Http2Stream has been destroyed, the http2stream.destroyed
property will be true and the http2stream.rstCode property will specify the
RST_STREAM error code. The Http2Stream instance is no longer usable once
destroyed.】
事件:'aborted'#>
【Event: 'aborted'】
'aborted' 事件在 Http2Stream 实例在通信过程中异常中止时触发。
其监听器不期望任何参数。
【The 'aborted' event is emitted whenever a Http2Stream instance is
abnormally aborted in mid-communication.
Its listener does not expect any arguments.】
'aborted' 事件只有在 Http2Stream 的可写端尚未结束时才会被触发。
【The 'aborted' event will only be emitted if the Http2Stream writable side
has not been ended.】
事件:'close'#>
【Event: 'close'】
'close' 事件在 Http2Stream 被销毁时触发。一旦该事件被触发,Http2Stream 实例将不再可用。
【The 'close' event is emitted when the Http2Stream is destroyed. Once
this event is emitted, the Http2Stream instance is no longer usable.】
关闭流时使用的 HTTP/2 错误代码可以通过 http2stream.rstCode 属性获取。如果代码的值不是 NGHTTP2_NO_ERROR(0),则还会触发一个 'error' 事件。
【The HTTP/2 error code used when closing the stream can be retrieved using
the http2stream.rstCode property. If the code is any value other than
NGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.】
事件:'错误'#>
【Event: 'error'】
error<Error>
当在处理 Http2Stream 时发生错误,会触发 'error' 事件。
【The 'error' event is emitted when an error occurs during the processing of
an Http2Stream.】
事件:'frameError'#>
【Event: 'frameError'】
当尝试发送帧时发生错误时,会触发 'frameError' 事件。调用时,处理函数将接收一个整数参数,标识帧类型,以及一个整数参数,标识错误码。在 'frameError' 事件触发后,Http2Stream 实例将立即被销毁。
【The 'frameError' event is emitted when an error occurs while attempting to
send a frame. When invoked, the handler function will receive an integer
argument identifying the frame type, and an integer argument identifying the
error code. The Http2Stream instance will be destroyed immediately after the
'frameError' event is emitted.】
事件:'ready'#>
【Event: 'ready'】
'ready' 事件在 Http2Stream 已打开、已分配 id 并可使用时触发。监听器不需要任何参数。
【The 'ready' event is emitted when the Http2Stream has been opened, has
been assigned an id, and can be used. The listener does not expect any
arguments.】
事件:'timeout'#>
【Event: 'timeout'】
'timeout' 事件会在此 Http2Stream 在指定毫秒数内没有接收到任何活动后触发,毫秒数通过 http2stream.setTimeout() 设置。它的监听器不需要任何参数。
【The 'timeout' event is emitted after no activity is received for this
Http2Stream within the number of milliseconds set using
http2stream.setTimeout().
Its listener does not expect any arguments.】
事件:'trailers'#>
【Event: 'trailers'】
headersHTTP/2 头对象 一个描述头信息的对象flags<number> 相关的数字标志
当接收到与尾随头字段相关的头块时,会触发 'trailers' 事件。监听器回调会接收到与这些头关联的 HTTP/2 头部对象 和标志。
【The 'trailers' event is emitted when a block of headers associated with
trailing header fields is received. The listener callback is passed the
HTTP/2 Headers Object and flags associated with the headers.】
如果在接收到尾部信息之前调用了 http2stream.end(),并且没有读取或监听传入的数据,则此事件可能不会被触发。
【This event might not be emitted if http2stream.end() is called
before trailers are received and the incoming data is not being read or
listened for.】
stream.on('trailers', (headers, flags) => {
console.log(headers);
});
事件:'wantTrailers'#>
【Event: 'wantTrailers'】
'wantTrailers' 事件在 Http2Stream 已将最终的 DATA 帧排队准备发送,并且 Http2Stream 已准备好发送尾随头时触发。在发起请求或响应时,必须将 waitForTrailers 选项设置为该事件才能被触发。
【The 'wantTrailers' event is emitted when the Http2Stream has queued the
final DATA frame to be sent on a frame and the Http2Stream is ready to send
trailing headers. When initiating a request or response, the waitForTrailers
option must be set for this event to be emitted.】
http2stream.aborted#>
- 类型:<boolean>
如果 Http2Stream 实例被异常中止,则设置为 true。设置后,'aborted' 事件将已经被触发。
【Set to true if the Http2Stream instance was aborted abnormally. When set,
the 'aborted' event will have been emitted.】
http2stream.bufferSize#>
- 类型:<number>
此属性显示当前缓冲区中待写入的字符数。有关详细信息,请参见 net.Socket.bufferSize。
【This property shows the number of characters currently buffered to be written.
See net.Socket.bufferSize for details.】
http2stream.close(code[, callback])#>
code<number> 无符号 32 位整数,用于标识错误代码。 默认值:http2.constants.NGHTTP2_NO_ERROR(0x00)。callback<Function> 一个可选的函数,用于注册以监听'close'事件。
通过向连接的 HTTP/2 对端发送 RST_STREAM 帧来关闭 Http2Stream 实例。
【Closes the Http2Stream instance by sending an RST_STREAM frame to the
connected HTTP/2 peer.】
http2stream.closed#>
- 类型:<boolean>
如果 Http2Stream 实例已关闭,则设置为 true。
【Set to true if the Http2Stream instance has been closed.】
http2stream.destroyed#>
- 类型:<boolean>
如果 Http2Stream 实例已被销毁且不再可用,设置为 true。
【Set to true if the Http2Stream instance has been destroyed and is no longer
usable.】
http2stream.endAfterHeaders#>
- 类型:<boolean>
如果在接收到的请求或响应 HEADERS 帧中设置了 END_STREAM 标志,将其设置为 true,表示不应接收额外数据,并且 Http2Stream 的可读端将被关闭。
【Set to true if the END_STREAM flag was set in the request or response
HEADERS frame received, indicating that no additional data should be received
and the readable side of the Http2Stream will be closed.】
http2stream.id#>
- 类型: <number> | <undefined>
此 Http2Stream 实例的数字流标识符。如果尚未分配流标识符,则设置为 undefined。
【The numeric stream identifier of this Http2Stream instance. Set to undefined
if the stream identifier has not yet been assigned.】
http2stream.pending#>
- 类型:<boolean>
如果 Http2Stream 实例尚未分配数字流标识符,则设置为 true。
【Set to true if the Http2Stream instance has not yet been assigned a
numeric stream identifier.】
http2stream.priority(options)#>
空方法,仅用于保持一定的向后兼容性。
【Empty method, only there to maintain some backward compatibility.】
http2stream.rstCode#>
- 类型:<number>
当 Http2Stream 在接收到来自连接端的 RST_STREAM 帧后被销毁,调用 http2stream.close() 或 http2stream.destroy() 后,将设置为报告的 RST_STREAM 错误代码。如果 Http2Stream 尚未关闭,则为 undefined。
【Set to the RST_STREAM error code reported when the Http2Stream is
destroyed after either receiving an RST_STREAM frame from the connected peer,
calling http2stream.close(), or http2stream.destroy(). Will be
undefined if the Http2Stream has not been closed.】
http2stream.sentHeaders#>
- 类型:HTTP/2 头对象
一个包含为此 Http2Stream 发送的出站头的对象。
【An object containing the outbound headers sent for this Http2Stream.】
http2stream.sentInfoHeaders#>
- 类型:HTTP/2 头对象[]
包含为该 Http2Stream 发送的出站信息(附加)头的对象数组。
【An array of objects containing the outbound informational (additional) headers
sent for this Http2Stream.】
http2stream.sentTrailers#>
- 类型:HTTP/2 头对象
一个包含为此 HttpStream 发送的出站 trailer 的对象。
【An object containing the outbound trailers sent for this HttpStream.】
http2stream.session#>
- 类型: <Http2Session>
引用拥有此 Http2Stream 的 Http2Session 实例。在 Http2Stream 实例被销毁后,该值将为 undefined。
【A reference to the Http2Session instance that owns this Http2Stream. The
value will be undefined after the Http2Stream instance is destroyed.】
http2stream.setTimeout(msecs, callback)#>
msecs<number>callback<Function>
import { connect, constants } from 'node:http2';
const client = connect('http://example.org:8000');
const { NGHTTP2_CANCEL } = constants;
const req = client.request({ ':path': '/' });
// Cancel the stream if there's no activity after 5 seconds
req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));const http2 = require('node:http2');
const client = http2.connect('http://example.org:8000');
const { NGHTTP2_CANCEL } = http2.constants;
const req = client.request({ ':path': '/' });
// Cancel the stream if there's no activity after 5 seconds
req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
http2stream.state#>
提供有关当前 Http2Stream 状态的各种信息。
【Provides miscellaneous information about the current state of the
Http2Stream.】
- 类型: <Object>
此 Http2Stream 的当前状态。
【A current state of this Http2Stream.】
http2stream.sendTrailers(headers)#>
headersHTTP/2 头对象
向已连接的 HTTP/2 对等端发送一个尾随的 HEADERS 帧。此方法会导致 Http2Stream 立即关闭,并且只能在 'wantTrailers' 事件触发后调用。在发送请求或响应时,必须设置 options.waitForTrailers 选项,以便在发送最后一个 DATA 帧后保持 Http2Stream 打开,从而可以发送尾随头。
【Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method
will cause the Http2Stream to be immediately closed and must only be
called after the 'wantTrailers' event has been emitted. When sending a
request or sending a response, the options.waitForTrailers option must be set
in order to keep the Http2Stream open after the final DATA frame so that
trailers can be sent.】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respond(undefined, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ xyz: 'abc' });
});
stream.end('Hello World');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respond(undefined, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ xyz: 'abc' });
});
stream.end('Hello World');
});
HTTP/1 规范禁止尾部包含 HTTP/2 伪头字段(例如 ':method'、':path' 等)。
【The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. ':method', ':path', etc).】
类:ClientHttp2Stream#>
【Class: ClientHttp2Stream】
ClientHttp2Stream 类是 Http2Stream 的扩展,专门用于 HTTP/2 客户端。客户端的 Http2Stream 实例提供诸如 'response' 和 'push' 等事件,这些事件仅在客户端相关。
【The ClientHttp2Stream class is an extension of Http2Stream that is
used exclusively on HTTP/2 Clients. Http2Stream instances on the client
provide events such as 'response' and 'push' that are only relevant on
the client.】
事件:'continue'#>
【Event: 'continue'】
当服务器发送 100 Continue 状态时触发,通常是因为请求中包含了 Expect: 100-continue。这是一个指示,告诉客户端应该发送请求主体。
【Emitted when the server sends a 100 Continue status, usually because
the request contained Expect: 100-continue. This is an instruction that
the client should send the request body.】
事件:'headers'#>
【Event: 'headers'】
headersHTTP/2 头对象flags<number>rawHeadersHTTP/2 原始头信息
'headers' 事件在接收到流的额外头块时触发,例如接收到一块 1xx 信息性头。监听器回调会传入与头关联的 HTTP/2 头部对象、标志,以及原始格式的头信息(见 HTTP/2 原始头)。
【The 'headers' event is emitted when an additional block of headers is received
for a stream, such as when a block of 1xx informational headers is received.
The listener callback is passed the HTTP/2 Headers Object, flags associated
with the headers, and the headers in raw format (see HTTP/2 Raw Headers).】
stream.on('headers', (headers, flags) => {
console.log(headers);
});
事件:'push'#>
【Event: 'push'】
headersHTTP/2 头对象flags<number>
'push' 事件在接收到服务器推送流的响应头时触发。监听器回调会传入与这些头相关的 HTTP/2 头部对象 和标志。
【The 'push' event is emitted when response headers for a Server Push stream
are received. The listener callback is passed the HTTP/2 Headers Object and
flags associated with the headers.】
stream.on('push', (headers, flags) => {
console.log(headers);
});
事件:'response'#>
【Event: 'response'】
headersHTTP/2 头对象flags<number>rawHeadersHTTP/2 原始头信息
当从已连接的 HTTP/2 服务器接收到响应的 HEADERS 帧时,会触发 'response' 事件。监听器会接收三个参数:一个包含接收到的 HTTP/2 头部对象 的 Object、与该头部相关的标志,以及原始格式的头部(见 HTTP/2 原始头)。
【The 'response' event is emitted when a response HEADERS frame has been
received for this stream from the connected HTTP/2 server. The listener is
invoked with three arguments: an Object containing the received
HTTP/2 Headers Object, flags associated with the headers, and the headers
in raw format (see HTTP/2 Raw Headers).】
import { connect } from 'node:http2';
const client = connect('https://localhost');
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
console.log(headers[':status']);
});const http2 = require('node:http2');
const client = http2.connect('https://localhost');
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
console.log(headers[':status']);
});
类:ServerHttp2Stream#>
【Class: ServerHttp2Stream】
ServerHttp2Stream 类是 Http2Stream 的扩展,专门用于 HTTP/2 服务器。服务器上的 Http2Stream 实例提供了额外的方法,例如 http2stream.pushStream() 和 http2stream.respond(),这些方法仅在服务器端相关。
【The ServerHttp2Stream class is an extension of Http2Stream that is
used exclusively on HTTP/2 Servers. Http2Stream instances on the server
provide additional methods such as http2stream.pushStream() and
http2stream.respond() that are only relevant on the server.】
http2stream.additionalHeaders(headers)#>
headersHTTP/2 头对象
向连接的 HTTP/2 对端发送一个额外的信息性 HEADERS 帧。
【Sends an additional informational HEADERS frame to the connected HTTP/2 peer.】
http2stream.headersSent#>
- 类型:<boolean>
如果标头被发送则为 true,否则为 false(只读)。
【True if headers were sent, false otherwise (read-only).】
http2stream.pushAllowed#>
- 类型:<boolean>
只读属性,映射到远程客户端最近的 SETTINGS 帧的 SETTINGS_ENABLE_PUSH 标志。如果远程对等端接受推送流,则为 true,否则为 false。在同一 Http2Session 中,每个 Http2Stream 的设置都是相同的。
【Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote
client's most recent SETTINGS frame. Will be true if the remote peer
accepts push streams, false otherwise. Settings are the same for every
Http2Stream in the same Http2Session.】
http2stream.pushStream(headers[, options], callback)#>
headersHTTP/2 头对象options<Object>callback<Function> 推送流启动后调用的回调函数。err<Error>pushStream<ServerHttp2Stream> 返回的pushStream对象。headersHTTP/2 Headers 对象pushStream启动时使用的 Headers 对象。
启动一个推送流。回调会被调用,并传入为推送流创建的新 Http2Stream 实例作为第二个参数,或者传入一个 Error 作为第一个参数。
【Initiates a push stream. The callback is invoked with the new Http2Stream
instance created for the push stream passed as the second argument, or an
Error passed as the first argument.】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 });
stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
if (err) throw err;
pushStream.respond({ ':status': 200 });
pushStream.end('some pushed data');
});
stream.end('some data');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 });
stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
if (err) throw err;
pushStream.respond({ ':status': 200 });
pushStream.end('some pushed data');
});
stream.end('some data');
});
在 HEADERS 帧中不允许设置推送流的权重。请将 weight 值传递给 http2stream.priority,并将 silent 选项设置为 true,以启用服务器端并发流之间的带宽平衡。
【Setting the weight of a push stream is not allowed in the HEADERS frame. Pass
a weight value to http2stream.priority with the silent option set to
true to enable server-side bandwidth balancing between concurrent streams.】
在已推送的流中调用 http2stream.pushStream() 是不允许的,会抛出错误。
【Calling http2stream.pushStream() from within a pushed stream is not permitted
and will throw an error.】
http2stream.respond([headers[, options]])#>
headersHTTP/2 请求头对象|HTTP/2 原始请求头options<Object>
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 });
stream.end('some data');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 });
stream.end('some data');
});
启动响应。当设置了 options.waitForTrailers 选项时,在将最后一块要发送的负载数据排入队列后,会立即触发 'wantTrailers' 事件。然后可以使用 http2stream.sendTrailers() 方法将尾部头字段发送给对端。
【Initiates a response. When the options.waitForTrailers option is set, the
'wantTrailers' event will be emitted immediately after queuing the last chunk
of payload data to be sent. The http2stream.sendTrailers() method can then be
used to sent trailing header fields to the peer.】
当设置 options.waitForTrailers 时,Http2Stream 在发送最后一个 DATA 帧后不会自动关闭。用户代码必须调用 http2stream.sendTrailers() 或 http2stream.close() 来关闭 Http2Stream。
【When options.waitForTrailers is set, the Http2Stream will not automatically
close when the final DATA frame is transmitted. User code must call either
http2stream.sendTrailers() or http2stream.close() to close the
Http2Stream.】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 }, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
stream.end('some data');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 }, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
stream.end('some data');
});
http2stream.respondWithFD(fd[, headers[, options]])#>
fd<number> | <FileHandle> 一个可读的文件描述符。headersHTTP/2 头对象options<Object>statCheck<Function>waitForTrailers<boolean> 当设置为true时,Http2Stream会在最后一个DATA帧发送后触发'wantTrailers'事件。offset<number> 开始读取的偏移位置。length<number> 要从文件描述符发送的数据量。
启动一个响应,其数据从给定的文件描述符读取。不会对给定的文件描述符进行任何验证。如果在使用文件描述符读取数据时发生错误,Http2Stream 将通过使用标准 INTERNAL_ERROR 代码的 RST_STREAM 帧关闭。
【Initiates a response whose data is read from the given file descriptor. No
validation is performed on the given file descriptor. If an error occurs while
attempting to read data using the file descriptor, the Http2Stream will be
closed using an RST_STREAM frame using the standard INTERNAL_ERROR code.】
使用时,Http2Stream 对象的 Duplex 接口将会被自动关闭。
【When used, the Http2Stream object's Duplex interface will be closed
automatically.】
import { createServer } from 'node:http2';
import { openSync, fstatSync, closeSync } from 'node:fs';
const server = createServer();
server.on('stream', (stream) => {
const fd = openSync('/some/file', 'r');
const stat = fstatSync(fd);
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers);
stream.on('close', () => closeSync(fd));
});const http2 = require('node:http2');
const fs = require('node:fs');
const server = http2.createServer();
server.on('stream', (stream) => {
const fd = fs.openSync('/some/file', 'r');
const stat = fs.fstatSync(fd);
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers);
stream.on('close', () => fs.closeSync(fd));
});
可以选择指定 options.statCheck 函数,以便用户代码有机会根据给定文件描述符的 fs.Stat 详细信息设置额外的内容头。如果提供了 statCheck 函数,http2stream.respondWithFD() 方法将执行 fs.fstat() 调用以收集提供的文件描述符的详细信息。
【The optional options.statCheck function may be specified to give user code
an opportunity to set additional content headers based on the fs.Stat details
of the given fd. If the statCheck function is provided, the
http2stream.respondWithFD() method will perform an fs.fstat() call to
collect details on the provided file descriptor.】
offset 和 length 选项可用于将响应限制在特定范围的子集。例如,这可以用于支持 HTTP 范围请求。
【The offset and length options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.】
流关闭时,文件描述符或 FileHandle 不会被关闭,因此在不再需要时需要手动关闭。 不支持在多个流中并发使用同一个文件描述符,并且可能导致数据丢失。 在流结束后重用文件描述符是支持的。
【The file descriptor or FileHandle is not closed when the stream is closed,
so it will need to be closed manually once it is no longer needed.
Using the same file descriptor concurrently for multiple streams
is not supported and may result in data loss. Re-using a file descriptor
after a stream has finished is supported.】
当设置 options.waitForTrailers 选项时,在将要发送的最后一块负载数据入队之后,将立即触发 'wantTrailers' 事件。然后可以使用 http2stream.sendTrailers() 方法向对端发送尾部头字段。
【When the options.waitForTrailers option is set, the 'wantTrailers' event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The http2stream.sendTrailers() method can then be used to sent trailing
header fields to the peer.】
当设置 options.waitForTrailers 时,Http2Stream 在最后的 DATA 帧发送完毕后不会自动关闭。用户代码必须调用 http2stream.sendTrailers() 或 http2stream.close() 来关闭 Http2Stream。
【When options.waitForTrailers is set, the Http2Stream will not automatically
close when the final DATA frame is transmitted. User code must call either
http2stream.sendTrailers() or http2stream.close() to close the
Http2Stream.】
import { createServer } from 'node:http2';
import { openSync, fstatSync, closeSync } from 'node:fs';
const server = createServer();
server.on('stream', (stream) => {
const fd = openSync('/some/file', 'r');
const stat = fstatSync(fd);
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
stream.on('close', () => closeSync(fd));
});const http2 = require('node:http2');
const fs = require('node:fs');
const server = http2.createServer();
server.on('stream', (stream) => {
const fd = fs.openSync('/some/file', 'r');
const stat = fs.fstatSync(fd);
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers, { waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
stream.on('close', () => fs.closeSync(fd));
});
http2stream.respondWithFile(path[, headers[, options]])#>
path<string> | <Buffer> | <URL>headersHTTP/2 头对象options<Object>statCheck<Function>onError<Function> 在发送前发生错误时调用的回调函数。waitForTrailers<boolean> 当设置为true时,Http2Stream会在最后一个DATA帧发送后触发'wantTrailers'事件。offset<number> 开始读取的偏移位置。length<number> 要从文件描述符发送的数据量。
将普通文件作为响应发送。path 必须指定一个普通文件,否则将在 Http2Stream 对象上触发 'error' 事件。
【Sends a regular file as the response. The path must specify a regular file
or an 'error' event will be emitted on the Http2Stream object.】
使用时,Http2Stream 对象的 Duplex 接口将会被自动关闭。
【When used, the Http2Stream object's Duplex interface will be closed
automatically.】
可以指定可选的 options.statCheck 函数,让用户代码有机会根据给定文件的 fs.Stat 详细信息设置额外的内容头:
【The optional options.statCheck function may be specified to give user code
an opportunity to set additional content headers based on the fs.Stat details
of the given file:】
如果在尝试读取文件数据时发生错误,Http2Stream 将使用 RST_STREAM 帧关闭,并使用标准的 INTERNAL_ERROR 代码。如果定义了 onError 回调,则会调用该回调。否则,流将被销毁。
【If an error occurs while attempting to read the file data, the Http2Stream
will be closed using an RST_STREAM frame using the standard INTERNAL_ERROR
code. If the onError callback is defined, then it will be called. Otherwise
the stream will be destroyed.】
使用文件路径的示例:
【Example using a file path:】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
function statCheck(stat, headers) {
headers['last-modified'] = stat.mtime.toUTCString();
}
function onError(err) {
// stream.respond() can throw if the stream has been destroyed by
// the other side.
try {
if (err.code === 'ENOENT') {
stream.respond({ ':status': 404 });
} else {
stream.respond({ ':status': 500 });
}
} catch (err) {
// Perform actual error handling.
console.error(err);
}
stream.end();
}
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ statCheck, onError });
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
function statCheck(stat, headers) {
headers['last-modified'] = stat.mtime.toUTCString();
}
function onError(err) {
// stream.respond() can throw if the stream has been destroyed by
// the other side.
try {
if (err.code === 'ENOENT') {
stream.respond({ ':status': 404 });
} else {
stream.respond({ ':status': 500 });
}
} catch (err) {
// Perform actual error handling.
console.error(err);
}
stream.end();
}
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ statCheck, onError });
});
options.statCheck 函数也可以通过返回 false 来取消发送操作。例如,条件请求可以检查 stat 结果,以确定文件是否已被修改,从而返回适当的 304 响应:
【The options.statCheck function may also be used to cancel the send operation
by returning false. For instance, a conditional request may check the stat
results to determine if the file has been modified to return an appropriate
304 response:】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
function statCheck(stat, headers) {
// Check the stat here...
stream.respond({ ':status': 304 });
return false; // Cancel the send operation
}
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ statCheck });
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
function statCheck(stat, headers) {
// Check the stat here...
stream.respond({ ':status': 304 });
return false; // Cancel the send operation
}
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ statCheck });
});
content-length 头字段将会自动设置。
【The content-length header field will be automatically set.】
offset 和 length 选项可用于将响应限制在特定范围的子集。例如,这可以用于支持 HTTP 范围请求。
【The offset and length options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.】
options.onError 函数也可以用来处理在文件传输开始之前可能发生的所有错误。默认行为是销毁流。
【The options.onError function may also be used to handle all the errors
that could happen before the delivery of the file is initiated. The
default behavior is to destroy the stream.】
当设置 options.waitForTrailers 选项时,在将要发送的最后一块负载数据入队之后,将立即触发 'wantTrailers' 事件。然后可以使用 http2stream.sendTrailers() 方法向对端发送尾部头字段。
【When the options.waitForTrailers option is set, the 'wantTrailers' event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The http2stream.sendTrailers() method can then be used to sent trailing
header fields to the peer.】
当设置 options.waitForTrailers 时,Http2Stream 在发送最后一个 DATA 帧后不会自动关闭。用户代码必须调用 http2stream.sendTrailers() 或 http2stream.close() 来关闭 Http2Stream。
【When options.waitForTrailers is set, the Http2Stream will not automatically
close when the final DATA frame is transmitted. User code must call either
http2stream.sendTrailers() or http2stream.close() to close the
Http2Stream.】
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});
类:Http2Server#>
【Class: Http2Server】
- 扩展自: <net.Server>
Http2Server 的实例是使用 http2.createServer() 函数创建的。Http2Server 类并未被 node:http2 模块直接导出。
【Instances of Http2Server are created using the http2.createServer()
function. The Http2Server class is not exported directly by the
node:http2 module.】
事件:'checkContinue'#>
【Event: 'checkContinue'】
request<http2.Http2ServerRequest>response<http2.Http2ServerResponse>
如果注册了 'request' 监听器或 http2.createServer() 提供了回调函数,每次收到带有 HTTP Expect: 100-continue 的请求时,都会触发 'checkContinue' 事件。如果没有监听此事件,服务器将自动根据情况响应 100 Continue 状态。
【If a 'request' listener is registered or http2.createServer() is
supplied a callback function, the 'checkContinue' event is 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 status
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.】
事件:'connection'#>
【Event: 'connection'】
socket<stream.Duplex>
当建立新的 TCP 流时,会触发此事件。socket 通常是 net.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.】
此事件也可以由用户显式触发,以向 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.】
事件:'request'#>
【Event: 'request'】
request<http2.Http2ServerRequest>response<http2.Http2ServerResponse>
每次有请求时都会触发。每个会话可能有多个请求。请参见 兼容性接口。
【Emitted each time there is a request. There may be multiple requests per session. See the Compatibility API.】
事件:'session'#>
【Event: 'session'】
session<ServerHttp2Session>
当 Http2Server 创建一个新的 Http2Session 时,会触发 'session' 事件。
【The 'session' event is emitted when a new Http2Session is created by the
Http2Server.】
事件:'sessionError'#>
【Event: 'sessionError'】
error<Error>session<ServerHttp2Session>
当与 Http2Server 关联的 Http2Session 对象发出 'error' 事件时,会触发 'sessionError' 事件。
【The 'sessionError' event is emitted when an 'error' event is emitted by
an Http2Session object associated with the Http2Server.】
事件:'stream'#>
【Event: 'stream'】
stream<Http2Stream> 对流的引用headersHTTP/2 头对象 一个描述头信息的对象flags<number> 相关的数字标志rawHeadersHTTP/2 原始头 一个包含原始头的数组
当与服务器关联的 Http2Session 发出 'stream' 事件时,会触发 'stream' 事件。
【The 'stream' event is emitted when a 'stream' event has been emitted by
an Http2Session associated with the server.】
【See also Http2Session's 'stream' event.】
import { createServer, constants } from 'node:http2';
const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_CONTENT_TYPE,
} = constants;
const server = createServer();
server.on('stream', (stream, headers, flags) => {
const method = headers[HTTP2_HEADER_METHOD];
const path = headers[HTTP2_HEADER_PATH];
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
[HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
});const http2 = require('node:http2');
const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const server = http2.createServer();
server.on('stream', (stream, headers, flags) => {
const method = headers[HTTP2_HEADER_METHOD];
const path = headers[HTTP2_HEADER_PATH];
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
[HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
});
事件:'timeout'#>
【Event: 'timeout'】
'timeout' 事件在服务器在设定的毫秒数内通过 http2server.setTimeout() 设置后没有活动时触发。
默认值: 0(无超时)
【The 'timeout' event is emitted when there is no activity on the Server for
a given number of milliseconds set using http2server.setTimeout().
Default: 0 (no timeout)】
server.close([callback])#>
callback<Function>
阻止服务器建立新的会话。这并不会因为 HTTP/2 会话的持久性而阻止创建新的请求流。要优雅地关闭服务器,请在所有活动会话上调用 http2session.close()。
【Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call http2session.close() on
all active sessions.】
如果提供了 callback,在所有活动会话关闭之前它不会被调用,尽管服务器已经停止允许新会话。更多详情请参见 net.Server.close()。
【If callback is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
net.Server.close() for more details.】
server[Symbol.asyncDispose]()#>
调用 server.close() 并返回一个在服务器关闭时完成的 Promise。
【Calls server.close() and returns a promise that fulfills when the
server has closed.】
server.setTimeout([msecs][, callback])#>
msecs<number> 默认值: 0(无限超时)callback<Function>- 返回:<Http2Server>
用于设置 http2 服务器请求的超时时间,并设置一个回调函数,当 Http2Server 在 msecs 毫秒后没有活动时调用该函数。
【Used to set the timeout value for http2 server requests,
and sets a callback function that is called when there is no activity
on the Http2Server after msecs milliseconds.】
给定的回调被注册为 'timeout' 事件的监听器。
【The given callback is registered as a listener on the 'timeout' event.】
如果 callback 不是一个函数,将抛出一个新的 ERR_INVALID_ARG_TYPE 错误。
【In case if callback is not a function, a new ERR_INVALID_ARG_TYPE
error will be thrown.】
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.updateSettings([settings])#>
settingsHTTP/2 设置对象
用于使用提供的设置更新服务器。
【Used to update the server with the provided settings.】
对于无效的 settings 值,会抛出 ERR_HTTP2_INVALID_SETTING_VALUE。
【Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.】
对于无效的 settings 参数会抛出 ERR_INVALID_ARG_TYPE。
【Throws ERR_INVALID_ARG_TYPE for invalid settings argument.】
类:Http2SecureServer#>
【Class: Http2SecureServer】
- 扩展自: <tls.Server>
Http2SecureServer 的实例是通过 http2.createSecureServer() 函数创建的。Http2SecureServer 类并没有被 node:http2 模块直接导出。
【Instances of Http2SecureServer are created using the
http2.createSecureServer() function. The Http2SecureServer class is not
exported directly by the node:http2 module.】
事件:'checkContinue'#>
【Event: 'checkContinue'】
request<http2.Http2ServerRequest>response<http2.Http2ServerResponse>
如果注册了 'request' 监听器或 http2.createSecureServer() 提供了回调函数,每次收到带有 HTTP Expect: 100-continue 的请求时,都会触发 'checkContinue' 事件。如果未监听此事件,服务器将自动适时地响应状态 100 Continue。
【If a 'request' listener is registered or http2.createSecureServer()
is supplied a callback function, the 'checkContinue' event is 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 status
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.】
事件:'connection'#>
【Event: 'connection'】
socket<stream.Duplex>
当建立新的 TCP 流时会触发此事件,在 TLS 握手开始之前。socket 通常是 net.Socket 类型的对象。通常用户不需要访问此事件。
【This event is emitted when a new TCP stream is established, before the TLS
handshake begins. socket is typically an object of type net.Socket.
Usually users will not want to access this event.】
此事件也可以由用户显式触发,以向 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.】
事件:'request'#>
【Event: 'request'】
request<http2.Http2ServerRequest>response<http2.Http2ServerResponse>
每次有请求时都会触发。每个会话可能有多个请求。请参见 兼容性接口。
【Emitted each time there is a request. There may be multiple requests per session. See the Compatibility API.】
事件:'session'#>
【Event: 'session'】
session<ServerHttp2Session>
当 Http2SecureServer 创建一个新的 Http2Session 时,会触发 'session' 事件。
【The 'session' event is emitted when a new Http2Session is created by the
Http2SecureServer.】
事件:'sessionError'#>
【Event: 'sessionError'】
error<Error>session<ServerHttp2Session>
'sessionError' 事件会在与 Http2SecureServer 关联的 Http2Session 对象触发 'error' 事件时被触发。
【The 'sessionError' event is emitted when an 'error' event is emitted by
an Http2Session object associated with the Http2SecureServer.】
事件:'stream'#>
【Event: 'stream'】
stream<Http2Stream> 对流的引用headersHTTP/2 头对象 一个描述头信息的对象flags<number> 相关的数字标志rawHeadersHTTP/2 原始头 一个包含原始头的数组
当与服务器关联的 Http2Session 发出 'stream' 事件时,会触发 'stream' 事件。
【The 'stream' event is emitted when a 'stream' event has been emitted by
an Http2Session associated with the server.】
【See also Http2Session's 'stream' event.】
import { createSecureServer, constants } from 'node:http2';
const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_CONTENT_TYPE,
} = constants;
const options = getOptionsSomehow();
const server = createSecureServer(options);
server.on('stream', (stream, headers, flags) => {
const method = headers[HTTP2_HEADER_METHOD];
const path = headers[HTTP2_HEADER_PATH];
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
[HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
});const http2 = require('node:http2');
const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const options = getOptionsSomehow();
const server = http2.createSecureServer(options);
server.on('stream', (stream, headers, flags) => {
const method = headers[HTTP2_HEADER_METHOD];
const path = headers[HTTP2_HEADER_PATH];
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
[HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
});
事件:'timeout'#>
【Event: 'timeout'】
'timeout' 事件会在服务器在设定的毫秒数内没有活动时触发,该毫秒数可通过 http2secureServer.setTimeout() 设置。
默认值: 2 分钟。
【The 'timeout' event is emitted when there is no activity on the Server for
a given number of milliseconds set using http2secureServer.setTimeout().
Default: 2 minutes.】
事件:'unknownProtocol'#>
【Event: 'unknownProtocol'】
socket<stream.Duplex>
当连接的客户端无法协商允许使用的协议(即 HTTP/2 或 HTTP/1.1)时,会触发 'unknownProtocol' 事件。事件处理程序会接收用于处理的套接字。如果未为此事件注册监听器,则连接将被终止。可以使用传递给 http2.createSecureServer() 的 'unknownProtocolTimeout' 选项指定超时时间。
【The 'unknownProtocol' event is emitted when a connecting client fails to
negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
receives the socket for handling. If no listener is registered for this event,
the connection is terminated. A timeout may be specified using the
'unknownProtocolTimeout' option passed to http2.createSecureServer().】
在较早版本的 Node.js 中,如果 allowHTTP1 为 false,并且在 TLS 握手过程中,客户端要么未发送 ALPN 扩展,要么发送的 ALPN 扩展不包含 HTTP/2(h2),则会触发此事件。Node.js 的新版本仅在 allowHTTP1 为 false 且客户端未发送 ALPN 扩展时才会触发此事件。如果客户端发送的 ALPN 扩展不包含 HTTP/2(或如果 allowHTTP1 为 true,则不包含 HTTP/1.1),TLS 握手将会失败,并且不会建立安全连接。
【In earlier versions of Node.js, this event would be emitted if allowHTTP1 is
false and, during the TLS handshake, the client either does not send an ALPN
extension or sends an ALPN extension that does not include HTTP/2 (h2). Newer
versions of Node.js only emit this event if allowHTTP1 is false and the
client does not send an ALPN extension. If the client sends an ALPN extension
that does not include HTTP/2 (or HTTP/1.1 if allowHTTP1 is true), the TLS
handshake will fail and no secure connection will be established.】
看 兼容性接口。
【See the Compatibility API.】
server.close([callback])#>
callback<Function>
阻止服务器建立新的会话。这并不会因为 HTTP/2 会话的持久性而阻止创建新的请求流。要优雅地关闭服务器,请在所有活动会话上调用 http2session.close()。
【Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call http2session.close() on
all active sessions.】
如果提供了 callback,在所有活动会话关闭之前它不会被调用,尽管服务器已经停止允许新会话。更多详情请参见 tls.Server.close()。
【If callback is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
tls.Server.close() for more details.】
server.setTimeout([msecs][, callback])#>
msecs<number> 默认值:120000(2分钟)callback<Function>- 返回:<Http2SecureServer>
用于设置 HTTP2 安全服务器请求的超时时间,并设置一个回调函数,当 Http2SecureServer 在 msecs 毫秒后没有活动时会被调用。
【Used to set the timeout value for http2 secure server requests,
and sets a callback function that is called when there is no activity
on the Http2SecureServer after msecs milliseconds.】
给定的回调被注册为 'timeout' 事件的监听器。
【The given callback is registered as a listener on the 'timeout' event.】
如果 callback 不是一个函数,将抛出一个新的 ERR_INVALID_ARG_TYPE 错误。
【In case if callback is not a function, a new ERR_INVALID_ARG_TYPE
error will be thrown.】
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.updateSettings([settings])#>
settingsHTTP/2 设置对象
用于使用提供的设置更新服务器。
【Used to update the server with the provided settings.】
对于无效的 settings 值,会抛出 ERR_HTTP2_INVALID_SETTING_VALUE。
【Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.】
对于无效的 settings 参数会抛出 ERR_INVALID_ARG_TYPE。
【Throws ERR_INVALID_ARG_TYPE for invalid settings argument.】
http2.createServer([options][, onRequestHandler])#>
options<Object>maxDeflateDynamicTableSize<number> 设置用于压缩头字段的最大动态表大小。默认值:4Kib。maxSettings<number> 设置每个SETTINGS帧的最大设置条目数量。允许的最小值为1。默认值:32。maxSessionMemory<number> 设置Http2Session允许使用的最大内存。该值以兆字节为单位,例如1表示 1 兆字节。允许的最小值为1。这是基于额度的限制,已有的Http2Stream可能会导致超过该限制,但在超出限制时,新的Http2Stream实例将被拒绝。当前Http2Stream会话的数量、头部压缩表的当前内存使用量、待发送的数据以及未确认的PING和SETTINGS帧都会计入当前限制。默认值:10。maxHeaderListPairs<number> 设置最大头部条目数。这类似于node:http模块中的server.maxHeadersCount或request.maxHeadersCount。最小值为4。默认值:128。maxOutstandingPings<number> 设置未确认 ping 的最大数量。默认值:10。maxSendHeaderBlockLength<number> 设置序列化、压缩头块的最大允许大小。尝试发送超过此限制的头部时,会触发'frameError'事件,并且流将被关闭和销毁。虽然这设置了整个头块的最大允许大小,但nghttp2(内部 http2 库)对每个解压后的键/值对的限制为65536。paddingStrategy<number> 用于确定HEADERS和DATA帧使用的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE。值可以是以下之一:http2.constants.PADDING_STRATEGY_NONE:不应用填充。http2.constants.PADDING_STRATEGY_MAX:由内部实现决定的最大填充量将被应用。http2.constants.PADDING_STRATEGY_ALIGNED:尝试应用足够的填充,以确保总帧长度(包括9字节的头部)是8的倍数。对于每个帧,允许的最大填充字节数由当前流量控制状态和设置决定。如果此最大值小于计算所需的对齐填充量,则使用最大值,并且总帧长度不一定对齐到8字节。
peerMaxConcurrentStreams<number> 设置远程对等方的最大并发流数量,就好像收到了SETTINGS帧一样。如果远程对等方为maxConcurrentStreams设置了自己的值,则此设置将被覆盖。默认值:100。maxSessionInvalidFrames<integer> 设置在会话关闭之前可以容忍的最大无效帧数。 默认值:1000。maxSessionRejectedStreams<integer> 设置在会话关闭之前,允许创建时被拒绝的最大流数量。每次拒绝都会伴随一个NGHTTP2_ENHANCE_YOUR_CALM错误,该错误应告知对端不要再打开更多流,因此继续打开流被视为对端行为异常。默认值:100。settingsHTTP/2 设置对象 与远程端建立连接时发送的初始设置。streamResetBurst<number> 和streamResetRate<number> 设置传入流重置(RST_STREAM 帧)的速率限制。两个设置都必须配置才能生效,默认值分别为 1000 和 33。remoteCustomSettings<Array> 整数值数组用于确定设置类型,这些类型包含在接收到的 remoteSettings 的CustomSettings属性中。有关允许的设置类型的详细信息,请参阅Http2Settings对象的CustomSettings属性。Http1IncomingMessage<http.IncomingMessage> 指定用于 HTTP/1 回退的IncomingMessage类。适用于扩展原始的http.IncomingMessage。默认值:http.IncomingMessage。Http1ServerResponse<http.ServerResponse> 指定用于 HTTP/1 回退的ServerResponse类。适用于扩展原始的http.ServerResponse。默认值:http.ServerResponse。Http2ServerRequest<http2.Http2ServerRequest> 指定要使用的Http2ServerRequest类。适用于扩展原始的Http2ServerRequest。默认值:Http2ServerRequest。Http2ServerResponse<http2.Http2ServerResponse> 指定要使用的Http2ServerResponse类。适用于扩展原始的Http2ServerResponse。默认值:Http2ServerResponse。unknownProtocolTimeout<number> 指定服务器在发出'unknownProtocol'时应等待的毫秒数超时。如果在该时间内套接字尚未被销毁,服务器将会销毁它。默认值:10000。strictFieldWhitespaceValidation<boolean> 如果为true,则会按照 RFC-9113 对 HTTP/2 头字段名称和值进行严格的前导和尾随空白验证。 默认值:true。...选项<Object> 可以提供任何net.createServer()选项。
onRequestHandler<Function> 参见 兼容性接口- 返回:<Http2Server>
返回一个 net.Server 实例,该实例创建并管理 Http2Session 实例。
【Returns a net.Server instance that creates and manages Http2Session
instances.】
由于目前没有已知的浏览器支持 未加密的 HTTP/2,因此在与浏览器客户端通信时必须使用 http2.createSecureServer()。
【Since there are no browsers known that support
unencrypted HTTP/2, the use of
http2.createSecureServer() is necessary when communicating
with browser clients.】
import { createServer } from 'node:http2';
// Create an unencrypted HTTP/2 server.
// Since there are no browsers known that support
// unencrypted HTTP/2, the use of `createSecureServer()`
// is necessary when communicating with browser clients.
const server = createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8000);const http2 = require('node:http2');
// Create an unencrypted HTTP/2 server.
// Since there are no browsers known that support
// unencrypted HTTP/2, the use of `http2.createSecureServer()`
// is necessary when communicating with browser clients.
const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8000);
http2.createSecureServer(options[, onRequestHandler])#>
options<Object>allowHTTP1<boolean> 当设置为true时,不支持 HTTP/2 的传入客户端连接将被降级为 HTTP/1.x。请参见'unknownProtocol'事件。参见 ALPN 协商。默认值:false。maxDeflateDynamicTableSize<number> 设置用于压缩头字段的最大动态表大小。默认值:4Kib。maxSettings<number> 设置每个SETTINGS帧的最大设置条目数量。允许的最小值为1。默认值:32。maxSessionMemory<number> 设置Http2Session允许使用的最大内存。该值以兆字节为单位,例如1表示 1 兆字节。允许的最小值为1。这是基于额度的限制,已有的Http2Stream可能会导致超过该限制,但在超出限制时,新的Http2Stream实例将被拒绝。当前Http2Stream会话的数量、头部压缩表的当前内存使用量、待发送的数据以及未确认的PING和SETTINGS帧都会计入当前限制。默认值:10。maxHeaderListPairs<number> 设置最大头部条目数。这类似于node:http模块中的server.maxHeadersCount或request.maxHeadersCount。最小值为4。默认值:128。maxOutstandingPings<number> 设置未确认 ping 的最大数量。默认值:10。maxSendHeaderBlockLength<number> 设置允许的序列化压缩头块的最大大小。尝试发送超过此限制的头部将导致触发'frameError'事件,并且流会被关闭和销毁。paddingStrategy<number> 用于确定HEADERS和DATA帧使用的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE。值可以是以下之一:http2.constants.PADDING_STRATEGY_NONE:不应用填充。http2.constants.PADDING_STRATEGY_MAX:由内部实现决定的最大填充量将被应用。http2.constants.PADDING_STRATEGY_ALIGNED:尝试应用足够的填充,以确保总帧长度(包括9字节的头部)是8的倍数。对于每个帧,允许的最大填充字节数由当前流量控制状态和设置决定。如果此最大值小于计算所需的对齐填充量,则使用最大值,并且总帧长度不一定对齐到8字节。
peerMaxConcurrentStreams<number> 设置远程对等方的最大并发流数量,就好像收到了SETTINGS帧一样。如果远程对等方为maxConcurrentStreams设置了自己的值,则此设置将被覆盖。默认值:100。maxSessionInvalidFrames<integer> 设置在会话关闭之前可以容忍的最大无效帧数。 默认值:1000。maxSessionRejectedStreams<integer> 设置在会话关闭之前,允许创建时被拒绝的最大流数量。每次拒绝都会伴随一个NGHTTP2_ENHANCE_YOUR_CALM错误,该错误应告知对端不要再打开更多流,因此继续打开流被视为对端行为异常。默认值:100。settingsHTTP/2 设置对象 与远程端建立连接时发送的初始设置。streamResetBurst<number> 和streamResetRate<number> 设置传入流重置(RST_STREAM 帧)的速率限制。两个设置都必须配置才能生效,默认值分别为 1000 和 33。remoteCustomSettings<Array> 整数值数组用于确定包含在接收到的remoteSettings的customSettings属性中的设置类型。有关允许的设置类型的更多信息,请参阅Http2Settings对象的customSettings属性。...options<Object> 可以提供任何tls.createServer()选项。对于服务器,通常需要身份选项(pfx或key/cert)。origins<string[]> 一个包含源字符串的数组,用于在创建新的服务器Http2Session后立即通过ORIGIN帧发送。unknownProtocolTimeout<number> 指定服务器在'unknownProtocol'事件触发时应等待的毫秒超时时间。如果在此时间内套接字尚未被销毁,服务器将会销毁它。默认值:10000。strictFieldWhitespaceValidation<boolean> 如果为true,则会按照 RFC-9113 对 HTTP/2 头字段名称和值进行严格的前导和尾随空白验证。 默认值:true。
onRequestHandler<Function> 参见 兼容性接口- 返回:<Http2SecureServer>
返回一个 tls.Server 实例,该实例创建并管理 Http2Session 实例。
【Returns a tls.Server instance that creates and manages Http2Session
instances.】
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const options = {
key: readFileSync('server-key.pem'),
cert: readFileSync('server-cert.pem'),
};
// Create a secure HTTP/2 server
const server = createSecureServer(options);
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);const http2 = require('node:http2');
const fs = require('node:fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
};
// Create a secure HTTP/2 server
const server = http2.createSecureServer(options);
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
http2.connect(authority[, options][, listener])#>
authority<string> | <URL> 要连接的远程 HTTP/2 服务器。必须采用最小的有效 URL 形式,包括http://或https://前缀、主机名以及 IP 端口(如果使用非默认端口)。URL 中的用户信息(用户 ID 和密码)、路径、查询字符串和片段将被忽略。options<Object>maxDeflateDynamicTableSize<number> 设置用于压缩头字段的最大动态表大小。默认值:4Kib。maxSettings<number> 设置每个SETTINGS帧的最大设置条目数量。允许的最小值为1。默认值:32。maxSessionMemory<number> 设置Http2Session允许使用的最大内存。该值以兆字节为单位,例如1表示 1 兆字节。允许的最小值为1。这是基于额度的限制,已有的Http2Stream可能会导致超过该限制,但在超出限制时,新的Http2Stream实例将被拒绝。当前Http2Stream会话的数量、头部压缩表的当前内存使用量、待发送的数据以及未确认的PING和SETTINGS帧都会计入当前限制。默认值:10。maxHeaderListPairs<number> 设置最大头部条目数。这类似于node:http模块中的server.maxHeadersCount或request.maxHeadersCount。最小值为1。默认值:128。maxOutstandingPings<number> 设置未确认 ping 的最大数量。默认值:10。maxReservedRemoteStreams<number> 设置客户端在任意时间可接受的最大保留推送流数量。一旦当前保留的推送流数量超过该限制,服务器发送的新推送流将被自动拒绝。允许的最小值是 0。允许的最大值是 232-1。负值会将此选项设置为允许的最大值。默认值:200。maxSendHeaderBlockLength<number> 设置允许的序列化压缩头块的最大大小。尝试发送超过此限制的头部将导致触发'frameError'事件,并且流会被关闭和销毁。paddingStrategy<number> 用于确定HEADERS和DATA帧使用的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE。值可以是以下之一:http2.constants.PADDING_STRATEGY_NONE:不应用填充。http2.constants.PADDING_STRATEGY_MAX:由内部实现决定的最大填充量将被应用。http2.constants.PADDING_STRATEGY_ALIGNED:尝试应用足够的填充,以确保总帧长度(包括9字节的头部)是8的倍数。对于每个帧,允许的最大填充字节数由当前流量控制状态和设置决定。如果此最大值小于计算所需的对齐填充量,则使用最大值,并且总帧长度不一定对齐到8字节。
peerMaxConcurrentStreams<number> 设置远程对等方的最大并发流数量,就好像收到了SETTINGS帧一样。如果远程对等方为maxConcurrentStreams设置了自己的值,则此设置将被覆盖。默认值:100。protocol<string> 用于连接的协议,如果在authority中未设置。取值可以是'http:'或'https:'。默认值:'https:'settingsHTTP/2 设置对象 与远程端建立连接时发送的初始设置。remoteCustomSettings<Array> 这个整数值数组用于确定包含在接收到的remoteSettings的CustomSettings属性中的设置类型。有关允许的设置类型的更多信息,请参阅Http2Settings对象的CustomSettings属性。createConnection<Function> 一个可选的回调函数,它接收传递给connect的URL实例和options对象,并返回用于此会话连接的任何Duplex流。...选项<Object> 可以提供任何net.connect()或tls.connect()选项。unknownProtocolTimeout<number> 指定服务器在'unknownProtocol'事件触发时应等待的毫秒超时时间。如果在此时间内套接字尚未被销毁,服务器将会销毁它。默认值:10000。strictFieldWhitespaceValidation<boolean> 如果为true,则会按照 RFC-9113 对 HTTP/2 头字段名称和值进行严格的前导和尾随空白验证。 默认值:true。
listener<Function> 将被注册为'connect'事件的一次性监听器。- 返回:<ClientHttp2Session>
返回一个 ClientHttp2Session 实例。
【Returns a ClientHttp2Session instance.】
import { connect } from 'node:http2';
const client = connect('https://localhost:1234');
/* Use the client */
client.close();const http2 = require('node:http2');
const client = http2.connect('https://localhost:1234');
/* Use the client */
client.close();
http2.constants#>
RST_STREAM 和 GOAWAY 的错误代码#>
【Error codes for RST_STREAM and GOAWAY】
| 值 | 名称 | 常量 |
|---|---|---|
0x00 | 无错误 | http2.constants.NGHTTP2_NO_ERROR |
0x01 | 协议错误 | http2.constants.NGHTTP2_PROTOCOL_ERROR |
0x02 | 内部错误 | http2.constants.NGHTTP2_INTERNAL_ERROR |
0x03 | 流量控制错误 | http2.constants.NGHTTP2_FLOW_CONTROL_ERROR |
0x04 | 设置超时 | http2.constants.NGHTTP2_SETTINGS_TIMEOUT |
0x05 | 流已关闭 | http2.constants.NGHTTP2_STREAM_CLOSED |
0x06 | 帧大小错误 | http2.constants.NGHTTP2_FRAME_SIZE_ERROR |
0x07 | 拒绝流 | http2.constants.NGHTTP2_REFUSED_STREAM |
0x08 | 取消 | http2.constants.NGHTTP2_CANCEL |
0x09 | 压缩错误 | http2.constants.NGHTTP2_COMPRESSION_ERROR |
0x0a | 连接错误 | http2.constants.NGHTTP2_CONNECT_ERROR |
0x0b | 保持冷静 | http2.constants.NGHTTP2_ENHANCE_YOUR_CALM |
0x0c | 安全不足 | http2.constants.NGHTTP2_INADEQUATE_SECURITY |
0x0d | 需要 HTTP/1.1 | http2.constants.NGHTTP2_HTTP_1_1_REQUIRED |
当服务器在通过 http2server.setTimeout() 设置的指定毫秒数内没有任何活动时,会触发 'timeout' 事件。
【The 'timeout' event is emitted when there is no activity on the Server for
a given number of milliseconds set using http2server.setTimeout().】
http2.getDefaultSettings()#>
- 返回:HTTP/2 设置对象
返回一个包含 Http2Session 实例默认设置的对象。每次调用此方法都会返回一个新的对象实例,因此返回的实例可以安全地进行修改以供使用。
【Returns an object containing the default settings for an Http2Session
instance. This method returns a new object instance every time it is called
so instances returned may be safely modified for use.】
http2.getPackedSettings([settings])#>
settingsHTTP/2 设置对象- 返回:<Buffer>
返回一个包含给定 HTTP/2 设置序列化表示的 Buffer 实例,如 HTTP/2 规范中所述。此方法旨在与 HTTP2-Settings 头字段一起使用。
【Returns a Buffer instance containing serialized representation of the given
HTTP/2 settings as specified in the HTTP/2 specification. This is intended
for use with the HTTP2-Settings header field.】
import { getPackedSettings } from 'node:http2';
const packed = getPackedSettings({ enablePush: false });
console.log(packed.toString('base64'));
// Prints: AAIAAAAAconst http2 = require('node:http2');
const packed = http2.getPackedSettings({ enablePush: false });
console.log(packed.toString('base64'));
// Prints: AAIAAAAA
http2.getUnpackedSettings(buf)#>
buf<Buffer> | <TypedArray> 已打包的设置。- 返回:HTTP/2 设置对象
返回一个 HTTP/2 设置对象,其中包含从给定 Buffer 反序列化的设置,该 Buffer 是由 http2.getPackedSettings() 生成的。
【Returns a HTTP/2 Settings Object containing the deserialized settings from
the given Buffer as generated by http2.getPackedSettings().】
http2.performServerHandshake(socket[, options])#>
socket<stream.Duplex>options<Object> 可以提供任何http2.createServer()选项。- 返回:<ServerHttp2Session>
从现有套接字创建 HTTP/2 服务器会话。
【Create an HTTP/2 server session from an existing socket.】
http2.sensitiveHeaders#>
- 类型: <symbol>
这个符号可以作为属性设置在 HTTP/2 头对象上,并使用数组值来提供被认为是敏感的头列表。有关更多详细信息,请参见 敏感标头。
【This symbol can be set as a property on the HTTP/2 headers object with an array value in order to provide a list of headers considered sensitive. See Sensitive headers for more details.】
标头对象#>
【Headers object】
头信息在 JavaScript 对象中表示为自身属性。属性键将被序列化为小写。属性值应为字符串(如果不是,将被强制转换为字符串)或字符串数组(以便每个头字段发送多个值)。
【Headers are represented as own-properties on JavaScript objects. The property
keys will be serialized to lower-case. Property values should be strings (if
they are not they will be coerced to strings) or an Array of strings (in order
to send more than one value per header field).】
const headers = {
':status': '200',
'content-type': 'text-plain',
'ABC': ['has', 'more', 'than', 'one', 'value'],
};
stream.respond(headers);
传递给回调函数的头对象将具有 null 原型。这意味着常规的 JavaScript 对象方法,如 Object.prototype.toString() 和 Object.prototype.hasOwnProperty() 将无法使用。
【Header objects passed to callback functions will have a null prototype. This
means that normal JavaScript object methods such as
Object.prototype.toString() and Object.prototype.hasOwnProperty() will
not work.】
对于传入的标头:
【For incoming headers:】
:status头会被转换为number。:status、:method、:authority、:scheme、:path、:protocol、age、authorization、access-control-allow-credentials、access-control-max-age、access-control-request-method、content-encoding、content-language、content-length、content-location、content-md5、content-range、content-type、date、dnt、etag、expires、from、host、if-match、if-modified-since、if-none-match、if-range、if-unmodified-since、last-modified、location、max-forwards、proxy-authorization、range、referer、retry-after、tk、upgrade-insecure-requests、user-agent 或 x-content-type-options 的重复项将被丢弃。set-cookie总是一个数组。重复项会被添加到数组中。- 对于重复的
cookie头,值会使用 '; ' 连接在一起。 - 对于所有其他标题,值将使用“, ”连接在一起。
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream, headers) => {
console.log(headers[':path']);
console.log(headers.ABC);
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream, headers) => {
console.log(headers[':path']);
console.log(headers.ABC);
});
原始标头#>
【Raw headers】
在某些 API 中,除了对象格式外,头信息还可以作为原始扁平数组传递或访问,以保留顺序和重复键的细节,以匹配原始传输格式。
【In some APIs, in addition to object format, headers can also be passed or accessed as a raw flat array, preserving details of ordering and duplicate keys to match the raw transmission format.】
在这种格式中,键和值在同一个列表中。它_不是_元组列表。因此,偶数位是键,奇数位是对应的值。重复的标题不会合并,因此每个键值对会单独出现。
【In this format 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. Duplicate headers are not merged and so each key-value pair will appear separately.】
这在某些情况下可能很有用,例如代理服务器,需要将现有的头信息完全按接收到的方式转发,或者当头信息已经以原始格式可用时,可用于性能优化。
【This can be useful for cases such as proxies, where existing headers should be exactly forwarded as received, or as a performance optimization when the headers are already available in raw format.】
const rawHeaders = [
':status',
'404',
'content-type',
'text/plain',
];
stream.respond(rawHeaders);
敏感标头#>
【Sensitive headers】
HTTP2 头可以被标记为敏感,这意味着 HTTP/2 头压缩算法永远不会对它们建立索引。这对于那些熵低且可能对攻击者有价值的头值是有意义的,例如 Cookie 或 Authorization。要实现这一点,将头名称作为数组添加到 [http2.sensitiveHeaders] 属性中:
【HTTP2 headers can be marked as sensitive, which means that the HTTP/2
header compression algorithm will never index them. This can make sense for
header values with low entropy and that may be considered valuable to an
attacker, for example Cookie or Authorization. To achieve this, add
the header name to the [http2.sensitiveHeaders] property as an array:】
const headers = {
':status': '200',
'content-type': 'text-plain',
'cookie': 'some-cookie',
'other-sensitive-header': 'very secret data',
[http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header'],
};
stream.respond(headers);
对于某些头,例如 Authorization 和短的 Cookie 头,该标志会自动设置。
【For some headers, such as Authorization and short Cookie headers,
this flag is set automatically.】
此属性也适用于接收到的头部。它将包含所有被标记为敏感的头部名称,包括那些自动标记为敏感的头部。
【This property is also set for received headers. It will contain the names of all headers marked as sensitive, including ones marked that way automatically.】
对于原始头,这仍然应作为数组的一个属性设置,例如 rawHeadersArray[http2.sensitiveHeaders] = ['cookie'],而不是在数组本身内作为单独的键值对。
【For raw headers, this should still be set as a property on the array, like
rawHeadersArray[http2.sensitiveHeaders] = ['cookie'], not as a separate key
and value pair within the array itself.】
设置对象#>
【Settings object】
http2.getDefaultSettings()、http2.getPackedSettings()、http2.createServer()、http2.createSecureServer()、http2session.settings()、http2session.localSettings 和 http2session.remoteSettings API 要么返回,要么接收一个作为输入的对象,该对象定义了 Http2Session 对象的配置设置。这些对象是普通的 JavaScript 对象,包含以下属性。
【The http2.getDefaultSettings(), http2.getPackedSettings(),
http2.createServer(), http2.createSecureServer(),
http2session.settings(), http2session.localSettings, and
http2session.remoteSettings APIs either return or receive as input an
object that defines configuration settings for an Http2Session object.
These objects are ordinary JavaScript objects containing the following
properties.】
headerTableSize<number> 指定用于头部压缩的最大字节数。允许的最小值为 0。允许的最大值为 232-1。默认值:4096。enablePush<boolean> 指定是否允许在Http2Session实例上使用 HTTP/2 推送流,如果允许,请设置为true。默认值:true。initialWindowSize<number> 指定 发送方 在流级流量控制中的初始窗口大小(以字节为单位)。允许的最小值是 0。允许的最大值是 232-1。默认值:65535。maxFrameSize<number> 指定最大帧有效负载的字节大小。允许的最小值为 16,384。允许的最大值为 224-1。默认值:16384。maxConcurrentStreams<number> 指定在Http2Session上允许的最大并发流数量。没有默认值,这意味着理论上,在任何给定时间,一个Http2Session中可以同时打开 232-1 个流。最小值为 0。允许的最大值为 232-1。默认值:4294967295。maxHeaderListSize<number> 指定将被接受的头列表的最大大小(未压缩字节)。允许的最小值为 0。允许的最大值为 232-1。默认值:65535。maxHeaderSize<number> 是maxHeaderListSize的别名。enableConnectProtocol<boolean> 如果要启用 RFC 8441 定义的“扩展连接协议”,则指定为true。此设置只有在服务器发送时才有意义。一旦为给定的Http2Session启用enableConnectProtocol设置,就无法禁用。默认值:false。customSettings<Object> 指定附加设置,但在 Node 及其底层库中尚未实现。对象的键定义了设置类型的数值(根据 [RFC 7540] 建立的 “HTTP/2 SETTINGS” 注册表),值为设置的实际数值。设置类型必须是从 1 到 2^16-1 范围内的整数。不应使用 Node 已处理的设置类型,即当前应大于 6,尽管这不是错误。值必须是从 0 到 2^32-1 的无符号整数。目前最多支持 10 个自定义设置。仅支持发送 SETTINGS,或接收在服务器或客户端对象的remoteCustomSettings选项中指定的设置值。在将来 Node 版本中,如果某个设置类型被本地支持,请不要将customSettings机制与本地处理的设置接口混用。
设置对象上的所有附加属性都将被忽略。
【All additional properties on the settings object are ignored.】
错误处理#>
【Error handling】
使用 node:http2 模块时,可能会出现几种类型的错误情况:
【There are several types of error conditions that may arise when using the
node:http2 module:】
当传入不正确的参数、选项或设置值时,会发生验证错误。这些错误总是通过同步 throw 报告。
【Validation errors occur when an incorrect argument, option, or setting value is
passed in. These will always be reported by a synchronous throw.】
状态错误发生在尝试在不正确的时间执行某个操作时(例如,在流关闭后尝试发送数据)。这些错误将通过同步的 throw 或在 Http2Stream、Http2Session 或 HTTP/2 服务器对象上触发的 'error' 事件来报告,具体取决于错误发生的地点和时间。
【State errors occur when an action is attempted at an incorrect time (for
instance, attempting to send data on a stream after it has closed). These will
be reported using either a synchronous throw or via an 'error' event on
the Http2Stream, Http2Session or HTTP/2 Server objects, depending on where
and when the error occurs.】
当 HTTP/2 会话意外失败时,会发生内部错误。这些错误将通过 Http2Session 或 HTTP/2 服务器对象上的 'error' 事件报告。
【Internal errors occur when an HTTP/2 session fails unexpectedly. These will be
reported via an 'error' event on the Http2Session or HTTP/2 Server objects.】
当违反各种 HTTP/2 协议约束时,会发生协议错误。
这些错误会通过同步 throw 抛出,或者在 Http2Stream、Http2Session 或 HTTP/2 服务器对象上通过 'error' 事件报告,具体取决于错误发生的地点和时间。
【Protocol errors occur when various HTTP/2 protocol constraints are violated.
These will be reported using either a synchronous throw or via an 'error'
event on the Http2Stream, Http2Session or HTTP/2 Server objects, depending
on where and when the error occurs.】
标头名称和值中的无效字符处理#>
【Invalid character handling in header names and values】
HTTP/2 实现对 HTTP 头名称和值中的无效字符处理比 HTTP/1 实现更严格。
【The HTTP/2 implementation applies stricter handling of invalid characters in HTTP header names and values than the HTTP/1 implementation.】
头字段名是 不区分大小写 的,并且在传输时严格作为小写字符串发送。Node.js 提供的 API 允许将头字段名设置为混合大小写的字符串(例如 Content-Type),但在传输时会将其转换为小写(例如 content-type)。
【Header field names are case-insensitive and are transmitted over the wire
strictly as lower-case strings. The API provided by Node.js allows header
names to be set as mixed-case strings (e.g. Content-Type) but will convert
those to lower-case (e.g. content-type) upon transmission.】
头字段名_必须只_包含以下 ASCII 字符之一或多个:a-z、A-Z、0-9、!、#、$、%、&、'、*、+、-、.、^、_、`(反引号)、| 和 ~。
【Header field-names must only contain one or more of the following ASCII
characters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,
-, ., ^, _, ` (backtick), |, and ~.】
在 HTTP 头字段名称中使用无效字符会导致流被关闭,并报告协议错误。
【Using invalid characters within an HTTP header field name will cause the stream to be closed with a protocol error being reported.】
根据 HTTP 规范的要求,HTTP 头字段值的处理更加宽松,但 不应 包含换行符或回车符,并且 应 限制为 US-ASCII 字符。
【Header field values are handled with more leniency but should not contain new-line or carriage return characters and should be limited to US-ASCII characters, per the requirements of the HTTP specification.】
在客户端推流#>
【Push streams on the client】
要在客户端接收推送的流,请在 ClientHttp2Session 上为 'stream' 事件设置一个监听器:
【To receive pushed streams on the client, set a listener for the 'stream'
event on the ClientHttp2Session:】
import { connect } from 'node:http2';
const client = connect('http://localhost');
client.on('stream', (pushedStream, requestHeaders) => {
pushedStream.on('push', (responseHeaders) => {
// Process response headers
});
pushedStream.on('data', (chunk) => { /* handle pushed data */ });
});
const req = client.request({ ':path': '/' });const http2 = require('node:http2');
const client = http2.connect('http://localhost');
client.on('stream', (pushedStream, requestHeaders) => {
pushedStream.on('push', (responseHeaders) => {
// Process response headers
});
pushedStream.on('data', (chunk) => { /* handle pushed data */ });
});
const req = client.request({ ':path': '/' });
支持 CONNECT 方法#>
【Supporting the CONNECT method】
CONNECT 方法用于允许将 HTTP/2 服务器用作 TCP/IP 连接的代理。
【The CONNECT method is used to allow an HTTP/2 server to be used as a proxy
for TCP/IP connections.】
简单的 TCP 服务器:
【A simple TCP Server:】
import { createServer } from 'node:net';
const server = createServer((socket) => {
let name = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => name += chunk);
socket.on('end', () => socket.end(`hello ${name}`));
});
server.listen(8000);const net = require('node:net');
const server = net.createServer((socket) => {
let name = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => name += chunk);
socket.on('end', () => socket.end(`hello ${name}`));
});
server.listen(8000);
HTTP/2 CONNECT 代理:
【An HTTP/2 CONNECT proxy:】
import { createServer, constants } from 'node:http2';
const { NGHTTP2_REFUSED_STREAM, NGHTTP2_CONNECT_ERROR } = constants;
import { connect } from 'node:net';
const proxy = createServer();
proxy.on('stream', (stream, headers) => {
if (headers[':method'] !== 'CONNECT') {
// Only accept CONNECT requests
stream.close(NGHTTP2_REFUSED_STREAM);
return;
}
const auth = new URL(`tcp://${headers[':authority']}`);
// It's a very good idea to verify that hostname and port are
// things this proxy should be connecting to.
const socket = connect(auth.port, auth.hostname, () => {
stream.respond();
socket.pipe(stream);
stream.pipe(socket);
});
socket.on('error', (error) => {
stream.close(NGHTTP2_CONNECT_ERROR);
});
});
proxy.listen(8001);const http2 = require('node:http2');
const { NGHTTP2_REFUSED_STREAM } = http2.constants;
const net = require('node:net');
const proxy = http2.createServer();
proxy.on('stream', (stream, headers) => {
if (headers[':method'] !== 'CONNECT') {
// Only accept CONNECT requests
stream.close(NGHTTP2_REFUSED_STREAM);
return;
}
const auth = new URL(`tcp://${headers[':authority']}`);
// It's a very good idea to verify that hostname and port are
// things this proxy should be connecting to.
const socket = net.connect(auth.port, auth.hostname, () => {
stream.respond();
socket.pipe(stream);
stream.pipe(socket);
});
socket.on('error', (error) => {
stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);
});
});
proxy.listen(8001);
HTTP/2 CONNECT 客户端:
【An HTTP/2 CONNECT client:】
import { connect, constants } from 'node:http2';
const client = connect('http://localhost:8001');
// Must not specify the ':path' and ':scheme' headers
// for CONNECT requests or an error will be thrown.
const req = client.request({
':method': 'CONNECT',
':authority': 'localhost:8000',
});
req.on('response', (headers) => {
console.log(headers[constants.HTTP2_HEADER_STATUS]);
});
let data = '';
req.setEncoding('utf8');
req.on('data', (chunk) => data += chunk);
req.on('end', () => {
console.log(`The server says: ${data}`);
client.close();
});
req.end('Jane');const http2 = require('node:http2');
const client = http2.connect('http://localhost:8001');
// Must not specify the ':path' and ':scheme' headers
// for CONNECT requests or an error will be thrown.
const req = client.request({
':method': 'CONNECT',
':authority': 'localhost:8000',
});
req.on('response', (headers) => {
console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);
});
let data = '';
req.setEncoding('utf8');
req.on('data', (chunk) => data += chunk);
req.on('end', () => {
console.log(`The server says: ${data}`);
client.close();
});
req.end('Jane');
扩展的 CONNECT 协议#>
【The extended CONNECT protocol】
RFC 8441 定义了一个“扩展 CONNECT 协议”扩展,用于 HTTP/2,可用于通过将 CONNECT 方法作为其他通信协议(如 WebSockets)的隧道来引导使用 Http2Stream。
HTTP/2 服务器通过使用 enableConnectProtocol 设置来启用扩展 CONNECT 协议的使用:
【The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using
the enableConnectProtocol setting:】
import { createServer } from 'node:http2';
const settings = { enableConnectProtocol: true };
const server = createServer({ settings });const http2 = require('node:http2');
const settings = { enableConnectProtocol: true };
const server = http2.createServer({ settings });
一旦客户端收到服务器发送的 SETTINGS 帧,表明可以使用扩展的 CONNECT,它就可以发送使用 ':protocol' HTTP/2 伪头的 CONNECT 请求:
【Once the client receives the SETTINGS frame from the server indicating that
the extended CONNECT may be used, it may send CONNECT requests that use the
':protocol' HTTP/2 pseudo-header:】
import { connect } from 'node:http2';
const client = connect('http://localhost:8080');
client.on('remoteSettings', (settings) => {
if (settings.enableConnectProtocol) {
const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });
// ...
}
});const http2 = require('node:http2');
const client = http2.connect('http://localhost:8080');
client.on('remoteSettings', (settings) => {
if (settings.enableConnectProtocol) {
const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });
// ...
}
});
兼容性接口#>
【Compatibility API】
兼容性 API 的目标是在使用 HTTP/2 时提供类似于 HTTP/1 的开发者体验,使得开发支持 HTTP/1 和 HTTP/2 的应用成为可能。该 API 仅针对 HTTP/1 的公共 API。然而,许多模块使用内部方法或状态,而这些不受支持,因为它是完全不同的实现。
【The Compatibility API has the goal of providing a similar developer experience of HTTP/1 when using HTTP/2, making it possible to develop applications that support both HTTP/1 and HTTP/2. This API targets only the public API of the HTTP/1. However many modules use internal methods or state, and those are not supported as it is a completely different implementation.】
以下示例使用兼容性 API 创建一个 HTTP/2 服务器:
【The following example creates an HTTP/2 server using the compatibility API:】
import { createServer } from 'node:http2';
const server = createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});const http2 = require('node:http2');
const server = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
要创建混合 HTTPS 和 HTTP/2 服务器,请参考 ALPN 协商 部分。 不支持从非 TLS 的 HTTP/1 服务器升级。
【In order to create a mixed HTTPS and HTTP/2 server, refer to the ALPN negotiation section. Upgrading from non-tls HTTP/1 servers is not supported.】
HTTP/2 兼容性 API 由 Http2ServerRequest 和 Http2ServerResponse 组成。它们旨在与 HTTP/1 保持 API 兼容,但并不隐藏协议之间的差异。例如,HTTP 状态码的状态消息会被忽略。
【The HTTP/2 compatibility API is composed of Http2ServerRequest and
Http2ServerResponse. They aim at API compatibility with HTTP/1, but
they do not hide the differences between the protocols. As an example,
the status message for HTTP codes is ignored.】
ALPN 协商#>
【ALPN negotiation】
ALPN 协商允许在同一个套接字上同时支持 HTTPS 和 HTTP/2。req 和 res 对象可以是 HTTP/1 或 HTTP/2,一个应用必须仅限于使用 HTTP/1 的公共 API,并检测是否可以使用 HTTP/2 的更高级功能。
【ALPN negotiation allows supporting both HTTPS and HTTP/2 over
the same socket. The req and res objects can be either HTTP/1 or
HTTP/2, and an application must restrict itself to the public API of
HTTP/1, and detect if it is possible to use the more advanced
features of HTTP/2.】
以下示例创建了支持两种协议的服务器:
【The following example creates a server that supports both protocols:】
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const cert = readFileSync('./cert.pem');
const key = readFileSync('./key.pem');
const server = createSecureServer(
{ cert, key, allowHTTP1: true },
onRequest,
).listen(8000);
function onRequest(req, res) {
// Detects if it is a HTTPS request or HTTP/2
const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
req.stream.session : req;
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({
alpnProtocol,
httpVersion: req.httpVersion,
}));
}const { createSecureServer } = require('node:http2');
const { readFileSync } = require('node:fs');
const cert = readFileSync('./cert.pem');
const key = readFileSync('./key.pem');
const server = createSecureServer(
{ cert, key, allowHTTP1: true },
onRequest,
).listen(4443);
function onRequest(req, res) {
// Detects if it is a HTTPS request or HTTP/2
const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
req.stream.session : req;
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({
alpnProtocol,
httpVersion: req.httpVersion,
}));
}
'request' 事件在 HTTPS 和 HTTP/2 上的工作方式完全相同。
【The 'request' event works identically on both HTTPS and
HTTP/2.】
类:http2.Http2ServerRequest#>
【Class: http2.Http2ServerRequest】
- 扩展自: <stream.Readable>
Http2ServerRequest 对象由 http2.Server 或 http2.SecureServer 创建,并作为第一个参数传递给 'request' 事件。它可用于访问请求状态、头信息和数据。
【A Http2ServerRequest object is created by http2.Server or
http2.SecureServer and passed as the first argument to the
'request' event. It may be used to access a request status, headers, and
data.】
事件:'aborted'#>
【Event: 'aborted'】
每当 Http2ServerRequest 实例在通信过程中被异常中止时,就会触发 'aborted' 事件。
【The 'aborted' event is emitted whenever a Http2ServerRequest instance is
abnormally aborted in mid-communication.】
'aborted' 事件只有在 Http2ServerRequest 的可写端未结束时才会触发。
【The 'aborted' event will only be emitted if the Http2ServerRequest writable
side has not been ended.】
事件:'close'#>
【Event: 'close'】
表示底层 Http2Stream 已关闭。就像 'end' 一样,此事件在每个响应中仅发生一次。
【Indicates that the underlying Http2Stream was closed.
Just like 'end', this event occurs only once per response.】
request.aborted#>
- 类型:<boolean>
request.aborted 属性将在请求被中止时为 true。
【The request.aborted property will be true if the request has
been aborted.】
request.authority#>
- 类型:<string>
请求的 authority 伪头字段。由于 HTTP/2 允许请求设置 :authority 或 host,如果存在 req.headers[':authority'],则该值从其派生。否则,它从 req.headers['host'] 派生。
【The request authority pseudo header field. Because HTTP/2 allows requests
to set either :authority or host, this value is derived from
req.headers[':authority'] if present. Otherwise, it is derived from
req.headers['host'].】
request.complete#>
- 类型:<boolean>
request.complete 属性将在请求已完成、被中止或被销毁时为 true。
【The request.complete property will be true if the request has
been completed, aborted, or destroyed.】
request.connection#>
request.socket。- 类型: <net.Socket> | <tls.TLSSocket>
【See request.socket.】
request.destroy([error])#>
error<Error>
对接收到 Http2ServerRequest 的 Http2Stream 调用 destroy()。如果提供了 error,将触发 'error' 事件,并将 error 作为参数传递给该事件的任何监听器。
【Calls destroy() on the Http2Stream that received
the Http2ServerRequest. If error is provided, an 'error' event
is emitted and error is passed as an argument to any listeners on the event.】
如果流已经被销毁,则什么也不做。
【It does nothing if the stream was already destroyed.】
request.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);
见 HTTP/2 头部对象。
【See HTTP/2 Headers Object.】
在 HTTP/2 中,请求路径、主机名、协议和方法表示为以 : 字符开头的特殊头(例如 ':path')。这些特殊头将包含在 request.headers 对象中。必须小心不要无意中修改这些特殊头,否则可能会发生错误。例如,从请求中删除所有头将导致错误发生:
【In HTTP/2, the request path, host name, protocol, and method are represented as
special headers prefixed with the : character (e.g. ':path'). These special
headers will be included in the request.headers object. Care must be taken not
to inadvertently modify these special headers or errors may occur. For instance,
removing all headers from the request will cause errors to occur:】
removeAllHeaders(request.headers);
assert(request.url); // Fails because the :path header has been removed
request.httpVersion#>
- 类型:<string>
在服务器请求的情况下,由客户端发送的HTTP版本。在客户端响应的情况下,为所连接服务器的HTTP版本。返回 '2.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. Returns
'2.0'.】
此外,message.httpVersionMajor 是第一个整数,而 message.httpVersionMinor 是第二个整数。
【Also message.httpVersionMajor is the first integer and
message.httpVersionMinor is the second.】
request.method#>
- 类型:<string>
请求方法,字符串类型。只读。示例:'GET'、'DELETE'。
【The request method as a string. Read-only. Examples: 'GET', 'DELETE'.】
request.rawHeaders#>
- 类型:HTTP/2 原始头
原始请求/响应头完全按照收到的方式列出。
【The raw request/response headers list exactly as they were received.】
// 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);
request.rawTrailers#>
- 类型: <string[]>
原始请求/响应的 trailer 键和值,与接收时完全相同。仅在 'end' 事件时填充。
【The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end' event.】
request.scheme#>
- 类型:<string>
请求方案伪头字段,指示目标 URL 的方案部分。
【The request scheme pseudo header field indicating the scheme portion of the target URL.】
request.setTimeout(msecs, callback)#>
msecs<number>callback<Function>- 返回:<http2.Http2ServerRequest>
将 Http2Stream 的超时值设置为 msecs。如果提供了回调函数,则会将其作为监听器添加到响应对象的 'timeout' 事件上。
【Sets the Http2Stream'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' 监听器,则在超时时,Http2Streams 会被销毁。如果为请求、响应或服务器的 'timeout' 事件分配了处理程序,则必须显式处理超时的套接字。
【If no 'timeout' listener is added to the request, the response, or
the server, then Http2Streams 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.】
request.socket#>
- 类型: <net.Socket> | <tls.TLSSocket>
返回一个 Proxy 对象,该对象表现得像一个 net.Socket(或 tls.TLSSocket),但会根据 HTTP/2 逻辑应用 getter、setter 和方法。
【Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but
applies getters, setters, and methods based on HTTP/2 logic.】
destroyed、readable 和 writable 属性将从 request.stream 中获取并设置。
destroy、emit、end、on 和 once 方法将被调用在 request.stream 上。
setTimeout 方法将会在 request.stream.session 上被调用。
pause、read、resume 和 write 会抛出错误,错误代码为 ERR_HTTP2_NO_SOCKET_MANIPULATION。更多信息请参见 Http2Session 和套接字。
所有其他交互将直接路由到套接字。使用 TLS 支持时,使用 request.socket.getPeerCertificate() 获取客户端的认证详情。
【All other interactions will be routed directly to the socket. With TLS support,
use request.socket.getPeerCertificate() to obtain the client's
authentication details.】
request.stream#>
- 类型: <Http2Stream>
支持该请求的 Http2Stream 对象。
【The Http2Stream object backing the request.】
request.trailers#>
- 类型: <Object>
请求/响应尾部对象。仅在 'end' 事件时填充。
【The request/response trailers object. Only populated at the 'end' event.】
request.url#>
- 类型:<string>
请求 URL 字符串。它仅包含实际 HTTP 请求中存在的 URL。如果请求是:
【Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:】
GET /status?name=ryan HTTP/1.1
Accept: text/plain
那么 request.url 将会是:
【Then request.url will be:】
'/status?name=ryan'
要将 URL 解析为各部分,可以使用 new URL():
【To parse the url into its parts, new URL() can be used:】
$ node
> new URL('/status?name=ryan', 'http://example.com')
URL {
href: 'http://example.com/status?name=ryan',
origin: 'http://example.com',
protocol: 'http:',
username: '',
password: '',
host: 'example.com',
hostname: 'example.com',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
类:http2.Http2ServerResponse#>
【Class: http2.Http2ServerResponse】
- 扩展:<Stream>
该对象由 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'】
表示在调用 response.end() 或能够刷新之前,底层的 Http2Stream 已被终止。
【Indicates that the underlying Http2Stream was terminated before
response.end() was called or able to flush.】
事件:'finish'#>
【Event: 'finish'】
当响应已发送时触发。更具体地说,当响应头和主体的最后一部分已交给 HTTP/2 多路复用以在网络上发送时,将触发此事件。这并不意味着客户端已经接收到任何内容。
【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 HTTP/2 multiplexing for transmission over the network. It does not imply that the client has received anything yet.】
在此事件之后,响应对象上将不再触发更多事件。
【After this event, no more events will be emitted on the response object.】
response.addTrailers(headers)#>
headers<Object>
该方法向响应添加 HTTP 尾部头(即消息末尾的头)。
【This method adds HTTP trailing headers (a header but at the end of the message) to the response.】
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
response.appendHeader(name, value)#>
name<string>value字符串|字符串数组
将单个标头值附加到标头对象。
【Append a single header value to the header object.】
如果值是数组,这相当于多次调用此方法。
【If the value is an array, this is equivalent to calling this method multiple times.】
如果该头部没有以前的值,这等同于调用 response.setHeader()。
【If there were no previous values for the header, this is equivalent to calling
response.setHeader().】
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
// Returns headers including "set-cookie: a" and "set-cookie: b"
const server = http2.createServer((req, res) => {
res.setHeader('set-cookie', 'a');
res.appendHeader('set-cookie', 'b');
res.writeHead(200);
res.end('ok');
});
response.connection#>
response.socket。- 类型: <net.Socket> | <tls.TLSSocket>
【See response.socket.】
response.createPushResponse(headers, callback)#>
headersHTTP/2 头对象 一个描述头信息的对象callback<Function> 当http2stream.pushStream()完成时调用,或者当尝试创建被推送的Http2Stream失败或被拒绝时调用,或者在调用http2stream.pushStream()方法之前Http2ServerRequest的状态已关闭err<Error>res<http2.Http2ServerResponse> 新创建的Http2ServerResponse对象
使用给定的头部调用 http2stream.pushStream(),并在成功时将给定的 Http2Stream 封装到新创建的 Http2ServerResponse 中作为回调参数。当 Http2ServerRequest 被关闭时,回调会带着错误 ERR_HTTP2_INVALID_STREAM 被调用。
【Call http2stream.pushStream() with the given headers, and wrap the
given Http2Stream on a newly created Http2ServerResponse as the callback
parameter if successful. When Http2ServerRequest is closed, the callback is
called with an error ERR_HTTP2_INVALID_STREAM.】
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 equivalent 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>
布尔值,用于指示响应是否已完成。初始为 false。在 response.end() 执行后,该值将为 true。
【Boolean value that indicates whether the response has completed. Starts
as false. After response.end() executes, the value will be true.】
response.getHeader(name)#>
读取已经排队但尚未发送给客户端的头信息。名称不区分大小写。
【Reads out a header that has already been queued but not sent to the client. The name is case-insensitive.】
const contentType = response.getHeader('content-type');
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>
如果标头被发送则为 true,否则为 false(只读)。
【True if headers were sent, false otherwise (read-only).】
response.removeHeader(name)#>
name<string>
删除已排队等待隐式发送的标头。
【Removes a header that has been queued for implicit sending.】
response.removeHeader('Content-Encoding');
response.req#>
对原始 HTTP2 request 对象的引用。
【A reference to the original HTTP2 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字符串|字符串数组
为隐式头设置单个头值。如果该头在即将发送的头中已经存在,其值将被替换。这里使用字符串数组可以发送多个具有相同名称的头。
【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.】
response.setHeader('Content-Type', 'text/html; charset=utf-8');
或者
【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 = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
response.setTimeout(msecs[, callback])#>
msecs<number>callback<Function>- 返回:<http2.Http2ServerResponse>
将 Http2Stream 的超时值设置为 msecs。如果提供了回调函数,则会将其作为监听器添加到响应对象的 'timeout' 事件上。
【Sets the Http2Stream'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' 监听器,则在超时时,Http2Streams 会被销毁。如果为请求、响应或服务器的 'timeout' 事件分配了处理程序,则必须显式处理超时的套接字。
【If no 'timeout' listener is added to the request, the response, or
the server, then Http2Streams 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#>
- 类型: <net.Socket> | <tls.TLSSocket>
返回一个 Proxy 对象,该对象表现得像一个 net.Socket(或 tls.TLSSocket),但会根据 HTTP/2 逻辑应用 getter、setter 和方法。
【Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but
applies getters, setters, and methods based on HTTP/2 logic.】
destroyed、readable 和 writable 属性将从 response.stream 中获取并设置。
destroy、emit、end、on 和 once 方法将被调用在 response.stream 上。
setTimeout 方法将会在 response.stream.session 上被调用。
pause、read、resume 和 write 会抛出错误,错误代码为 ERR_HTTP2_NO_SOCKET_MANIPULATION。更多信息请参见 Http2Session 和套接字。
所有其他交互将直接路由到套接字。
【All other interactions will be routed directly to the socket.】
import { createServer } from 'node:http2';
const server = createServer((req, res) => {
const ip = req.socket.remoteAddress;
const port = req.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);const http2 = require('node:http2');
const server = http2.createServer((req, res) => {
const ip = req.socket.remoteAddress;
const port = req.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
response.statusCode#>
- 类型:<number>
在使用隐式头(未显式调用 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>
状态消息不被 HTTP/2(RFC 7540 8.1.2.4)支持。它会返回一个空字符串。
【Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns an empty string.】
response.stream#>
- 类型: <Http2Stream>
支持响应的Http2Stream对象。
【The Http2Stream object backing the response.】
response.writableEnded#>
- 类型:<boolean>
[response.end()][response.end()] 被调用后为 true。此属性并不表示数据是否已刷新,如需检查数据是否已刷新,请改用 writable.writableFinished。
【Is true after response.end() has been called. This property
does not indicate whether the data has been flushed, for this use
writable.writableFinished instead.】
response.write(chunk[, encoding][, callback])#>
chunk<string> | <Buffer> | <Uint8Array>encoding<string>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.】
在 node:http 模块中,当请求是 HEAD 请求时,响应体会被省略。类似地,204 和 304 响应_必须不_包含消息体。
【In the node:http module, the response body is omitted when the
request is a HEAD request. Similarly, the 204 and 304 responses
must not include a message body.】
chunk 可以是字符串或缓冲区。如果 chunk 是字符串,第二个参数指定如何将其编码为字节流。默认情况下,encoding 为 'utf8'。当这块数据被刷新时,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()#>
向客户端发送状态 100 Continue,表示应该发送请求体。请参阅 Http2Server 和 Http2SecureServer 上的 'checkContinue' 事件。
【Sends a status 100 Continue to the client, indicating that the request body
should be sent. See the 'checkContinue' event on Http2Server and
Http2SecureServer.】
response.writeEarlyHints(hints)#>
hints<Object>
向客户端发送状态 103 Early Hints,并带有 Link 头,表示用户代理可以预加载/预连接所链接的资源。hints 是一个对象,包含要随早期提示消息发送的头部值。
【Sends a status 103 Early Hints 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.】
示例
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,
});
response.writeHead(statusCode[, statusMessage][, headers])#>
statusCode<number>statusMessage<string>headersHTTP/2 请求头对象|HTTP/2 原始请求头- 返回:<http2.Http2ServerResponse>
向请求发送响应头。状态码是一个三位数的 HTTP 状态码,例如 404。最后一个参数 headers 是响应头。
【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.】
返回 Http2ServerResponse 的引用,以便可以进行链式调用。
【Returns a reference to the Http2ServerResponse, so that calls can be chained.】
为了与 HTTP/1 兼容,可以将可读的 statusMessage 作为第二个参数传入。然而,由于 statusMessage 在 HTTP/2 中没有实际意义,该参数将不会产生任何效果,并且会触发进程警告。
【For compatibility with HTTP/1, a human-readable statusMessage may be
passed as the second argument. However, because the statusMessage has no
meaning within HTTP/2, the argument will have no effect and a process warning
will be emitted.】
const body = 'hello world';
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain; charset=utf-8',
});
Content-Length 是以字节为单位而不是字符。可以使用 Buffer.byteLength() API 来确定特定编码下的字节数。在发送消息时,Node.js 不会检查 Content-Length 与传输的主体长度是否相等。然而,在接收消息时,当 Content-Length 与实际负载大小不匹配时,Node.js 会自动拒绝该消息。
在调用 response.end() 之前,这个方法最多只能在一条消息上调用一次。
【This method may be called at most one time on a message 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.】
// Returns content-type = text/plain
const server = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
收集 HTTP/2 性能指标#>
【Collecting HTTP/2 performance metrics】
性能监视器 API 可用于收集每个 Http2Session 和 Http2Stream 实例的基本性能指标。
【The Performance Observer API can be used to collect basic performance
metrics for each Http2Session and Http2Stream instance.】
import { PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((items) => {
const entry = items.getEntries()[0];
console.log(entry.entryType); // prints 'http2'
if (entry.name === 'Http2Session') {
// Entry contains statistics about the Http2Session
} else if (entry.name === 'Http2Stream') {
// Entry contains statistics about the Http2Stream
}
});
obs.observe({ entryTypes: ['http2'] });const { PerformanceObserver } = require('node:perf_hooks');
const obs = new PerformanceObserver((items) => {
const entry = items.getEntries()[0];
console.log(entry.entryType); // prints 'http2'
if (entry.name === 'Http2Session') {
// Entry contains statistics about the Http2Session
} else if (entry.name === 'Http2Stream') {
// Entry contains statistics about the Http2Stream
}
});
obs.observe({ entryTypes: ['http2'] });
PerformanceEntry 的 entryType 属性将等于 'http2'。
【The entryType property of the PerformanceEntry will be equal to 'http2'.】
PerformanceEntry 的 name 属性将等于 'Http2Stream' 或 'Http2Session'。
【The name property of the PerformanceEntry will be equal to either
'Http2Stream' or 'Http2Session'.】
如果 name 等于 Http2Stream,PerformanceEntry 将包含以下附加属性:
【If name is equal to Http2Stream, the PerformanceEntry will contain the
following additional properties:】
bytesRead<number> 接收到的此Http2Stream的DATA帧字节数。bytesWritten<number> 此Http2Stream发送的DATA帧字节数。id<number> 关联Http2Stream的标识符timeToFirstByte<number> 从PerformanceEntry的startTime到接收到第一个DATA帧所经过的毫秒数。timeToFirstByteSent<number> 从PerformanceEntry的startTime到发送第一个DATA帧所经过的毫秒数。timeToFirstHeader<number> 从PerformanceEntry的startTime到接收到第一个响应头经过的毫秒数。
如果 name 等于 Http2Session,PerformanceEntry 将包含以下附加属性:
【If name is equal to Http2Session, the PerformanceEntry will contain the
following additional properties:】
bytesRead<number> 此Http2Session接收到的字节数。bytesWritten<number> 发送到此Http2Session的字节数。framesReceived<number>Http2Session接收到的 HTTP/2 帧的数量。framesSent<number>Http2Session发送的 HTTP/2 帧的数量。maxConcurrentStreams<number> 在Http2Session生命周期中可以同时打开的最大流数。pingRTT<number> 自发送PING帧到接收到其确认所经过的毫秒数。仅在已在Http2Session上发送过PING帧时才会出现。streamAverageDuration<number> 所有Http2Stream实例的平均持续时间(以毫秒为单位)。streamCount<number>Http2Session处理的Http2Stream实例数量。type<string> 可以是'server'或'client',用于标识Http2Session的类型。
关于 :authority 和 host 的说明#>
【Note on :authority and host】
HTTP/2 要求请求必须包含 :authority 伪头部或 host 头部。在直接构建 HTTP/2 请求时,优先使用 :authority;在从 HTTP/1 转换时(例如在代理中),优先使用 host。
【HTTP/2 requires requests to have either the :authority pseudo-header
or the host header. Prefer :authority when constructing an HTTP/2
request directly, and host when converting from HTTP/1 (in proxies,
for instance).】
如果没有 :authority,兼容性 API 会回退到 host。更多信息请参见 request.authority。然而,如果你不使用兼容性 API(或直接使用 req.headers),你需要自己实现任何回退行为。
【The compatibility API falls back to host if :authority is not
present. See request.authority for more information. However,
if you don't use the compatibility API (or use req.headers directly),
you need to implement any fall-back behavior yourself.】