- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- 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 v22.12.0 文档
- Node.js v22.12.0
-
目录
- HTTP/2
- 确定加密支持是否不可用
- 核心接口
- 服务器端示例
- 客户端示例
- 类:
Http2Session
Http2Session
和套接字- 事件:
'close'
- 事件:
'connect'
- 事件:
'error'
- 事件:
'frameError'
- 事件:
'goaway'
- 事件:
'localSettings'
- 事件:
'ping'
- 事件:
'remoteSettings'
- 事件:
'stream'
- 事件:
'timeout'
http2session.alpnProtocol
http2session.close([callback])
http2session.closed
http2session.connecting
http2session.destroy([error][, code])
http2session.destroyed
http2session.encrypted
http2session.goaway([code[, lastStreamID[, opaqueData]]])
http2session.localSettings
http2session.originSet
http2session.pendingSettingsAck
http2session.ping([payload, ]callback)
http2session.ref()
http2session.remoteSettings
http2session.setLocalWindowSize(windowSize)
http2session.setTimeout(msecs, callback)
http2session.socket
http2session.state
http2session.settings([settings][, callback])
http2session.type
http2session.unref()
- 类:
ServerHttp2Session
- 类:
ClientHttp2Session
- 类:
Http2Stream
Http2Stream
生命周期- 事件:
'aborted'
- 事件:
'close'
- 事件:
'error'
- 事件:
'frameError'
- 事件:
'ready'
- 事件:
'timeout'
- 事件:
'trailers'
- 事件:
'wantTrailers'
http2stream.aborted
http2stream.bufferSize
http2stream.close(code[, callback])
http2stream.closed
http2stream.destroyed
http2stream.endAfterHeaders
http2stream.id
http2stream.pending
http2stream.priority(options)
http2stream.rstCode
http2stream.sentHeaders
http2stream.sentInfoHeaders
http2stream.sentTrailers
http2stream.session
http2stream.setTimeout(msecs, callback)
http2stream.state
http2stream.sendTrailers(headers)
- 类:
ClientHttp2Stream
- 类:
ServerHttp2Stream
- 类:
Http2Server
- 类:
Http2SecureServer
http2.createServer([options][, onRequestHandler])
http2.createSecureServer(options[, onRequestHandler])
http2.connect(authority[, options][, listener])
http2.constants
http2.getDefaultSettings()
http2.getPackedSettings([settings])
http2.getUnpackedSettings(buf)
http2.performServerHandshake(socket[, options])
http2.sensitiveHeaders
- 标头对象
- 设置对象
- 错误处理
- 标头名称和值中的无效字符处理
- 在客户端推流
- 支持
CONNECT
方法 - 扩展的
CONNECT
协议
- 兼容性接口
- ALPN 协商
- 类:
http2.Http2ServerRequest
- 事件:
'aborted'
- 事件:
'close'
request.aborted
request.authority
request.complete
request.connection
request.destroy([error])
request.headers
request.httpVersion
request.method
request.rawHeaders
request.rawTrailers
request.scheme
request.setTimeout(msecs, callback)
request.socket
request.stream
request.trailers
request.url
- 事件:
- 类:
http2.Http2ServerResponse
- 事件:
'close'
- 事件:
'finish'
response.addTrailers(headers)
response.appendHeader(name, value)
response.connection
response.createPushResponse(headers, callback)
response.end([data[, encoding]][, callback])
response.finished
response.getHeader(name)
response.getHeaderNames()
response.getHeaders()
response.hasHeader(name)
response.headersSent
response.removeHeader(name)
response.req
response.sendDate
response.setHeader(name, value)
response.setTimeout(msecs[, callback])
response.socket
response.statusCode
response.statusMessage
response.stream
response.writableEnded
response.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 控制台
- Corepack 核心包
- 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#
¥Stability: 2 - Stable
源代码: 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:crypto
模块的情况下构建 Node.js。在这种情况下,尝试 import
node:http2
或调用 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.
与 http
API 相比,http2
核心 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
以下说明了使用核心 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
-
¥Extends: <EventEmitter>
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.
事件:'error'
#
¥Event: 'error'
error
<Error>
'error'
事件在处理 Http2Session
期间发生错误时触发。
¥The 'error'
event is emitted when an error occurs during the processing of
an Http2Session
.
事件:'frameError'
#
¥Event: 'frameError'
-
type
<integer> 帧类型。¥
type
<integer> The frame type. -
code
<integer> 错误代码。¥
code
<integer> The error code. -
id
<integer> 流 id(或如果帧不与流相关联,则为0
)。¥
id
<integer> The stream id (or0
if the frame isn't associated with a stream).
当尝试在会话上发送帧时发生错误时会触发 '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 错误代码。¥
errorCode
<number> The HTTP/2 error code specified in theGOAWAY
frame. -
lastStreamID
<number> 远程对等方成功处理的最后一个流的 ID(如果未指定 ID,则为0
)。¥
lastStreamID
<number> The ID of the last stream the remote peer successfully processed (or0
if no ID is specified). -
opaqueData
<Buffer> 如果GOAWAY
帧中包含其他不透明数据,则将传入包含该数据的Buffer
实例。¥
opaqueData
<Buffer> If additional opaque data was included in theGOAWAY
frame, aBuffer
instance will be passed containing that data.
接收到 GOAWAY
帧时触发 'goaway'
事件。
¥The 'goaway'
event is emitted when a GOAWAY
frame is received.
'goaway'
事件触发时,Http2Session
实例会自动关闭。
¥The Http2Session
instance will be shut down automatically when the 'goaway'
event is emitted.
事件:'localSettings'
#
¥Event: 'localSettings'
-
settings
<HTTP/2 Settings Object> 接收到了SETTINGS
帧的副本。¥
settings
<HTTP/2 Settings Object> A copy of theSETTINGS
frame received.
当接收到确认 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'
每当从连接的对等方接收到 PING
帧时,则会触发 'ping'
事件。
¥The 'ping'
event is emitted whenever a PING
frame is received from the
connected peer.
事件:'remoteSettings'
#
¥Event: 'remoteSettings'
-
settings
<HTTP/2 Settings Object> 接收到了SETTINGS
帧的副本。¥
settings
<HTTP/2 Settings Object> A copy of theSETTINGS
frame received.
当从连接的对等方接收到新的 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> 对流的引用¥
stream
<Http2Stream> A reference to the stream -
headers
<HTTP/2 Headers Object> 描述标头的对象¥
headers
<HTTP/2 Headers Object> An object describing the headers -
flags
<number> 相关的数字标志¥
flags
<number> The associated numeric flags -
rawHeaders
<Array> 包含原始标头名称后跟它们各自值的数组。¥
rawHeaders
<Array> An array containing the raw header names followed by their respective values.
创建新的 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 流和网络套接字不是 1:1 对应关系,网络错误也会销毁每个单独的流,并且必须在流级别进行处理,如上所示。
¥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
#
如果 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
#
如果此 Http2Session
实例已关闭,则为 true
,否则为 false
。
¥Will be true
if this Http2Session
instance has been closed, otherwise
false
.
http2session.connecting
#
如果此 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
对象。¥
error
<Error> AnError
object if theHttp2Session
is being destroyed due to an error. -
code
<number> 要在最终GOAWAY
帧中发送的 HTTP/2 错误代码。如果未指定,且error
未未定义,则默认为INTERNAL_ERROR
,否则默认为NO_ERROR
。¥
code
<number> The HTTP/2 error code to send in the finalGOAWAY
frame. If unspecified, anderror
is not undefined, the default isINTERNAL_ERROR
, otherwise defaults toNO_ERROR
.
立即终止 Http2Session
和相关联的 net.Socket
或 tls.TLSSocket
。
¥Immediately terminates the Http2Session
and the associated net.Socket
or
tls.TLSSocket
.
一旦销毁,则 Http2Session
将触发 'close'
事件。如果 error
未定义,则将在 'close'
事件之前立即触发 'error'
事件。
¥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
#
如果此 Http2Session
实例已被销毁且不能再使用,则为 true
,否则为 false
。
¥Will be true
if this Http2Session
instance has been destroyed and must no
longer be used, otherwise false
.
http2session.encrypted
#
如果 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 错误代码¥
code
<number> An HTTP/2 error code -
lastStreamID
<number> 最后处理的Http2Stream
的数字 ID¥
lastStreamID
<number> The numeric ID of the last processedHttp2Stream
-
opaqueData
<Buffer> | <TypedArray> | <DataView>TypedArray
或DataView
实例,包含要在GOAWAY
帧中携带的附加数据。¥
opaqueData
<Buffer> | <TypedArray> | <DataView> ATypedArray
orDataView
instance containing additional data to be carried within theGOAWAY
frame.
在不关闭 Http2Session
的情况下将 GOAWAY
帧传输到连接的对等方。
¥Transmits a GOAWAY
frame to the connected peer without shutting down the
Http2Session
.
http2session.localSettings
#
描述此 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
#
如果 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
#
指示 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 负载。¥
payload
<Buffer> | <TypedArray> | <DataView> Optional ping payload. -
callback
<Function> -
返回:<boolean>
¥Returns: <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.
未完成的(未确认的)ping 的最大数量由 maxOutstandingPings
配置选项决定。默认最大值为 10。
¥The maximum number of outstanding (unacknowledged) pings is determined by the
maxOutstandingPings
configuration option. The default maximum is 10.
如果提供,则 payload
必须是 Buffer
、TypedArray
或 DataView
,其中包含 8 个字节的数据,这些数据将与 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
#
描述此 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>
用于设置 msecs
毫秒后 Http2Session
上没有活动时调用的回调函数。给定的 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
#
返回 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
和套接字。
¥destroy
, emit
, end
, pause
, read
, resume
, and write
will throw
an error with code ERR_HTTP2_NO_SOCKET_MANIPULATION
. See
Http2Session
and Sockets for more information.
将在此 Http2Session
上调用 setTimeout
方法。
¥setTimeout
method will be called on this Http2Session
.
所有其他交互将直接路由到套接字。
¥All other interactions will be routed directly to the socket.
http2session.state
#
提供有关 Http2Session
当前状态的其他信息。
¥Provides miscellaneous information about the current state of the
Http2Session
.
-
-
effectiveLocalWindowSize
<number>Http2Session
的当前本地(接收)流控制窗口大小。¥
effectiveLocalWindowSize
<number> The current local (receive) flow control window size for theHttp2Session
. -
effectiveRecvDataLength
<number> 自上次流控制WINDOW_UPDATE
以来已接收的当前字节数。¥
effectiveRecvDataLength
<number> The current number of bytes that have been received since the last flow controlWINDOW_UPDATE
. -
nextStreamID
<number> 下一次此Http2Session
创建新Http2Stream
时要使用的数字标识符。¥
nextStreamID
<number> The numeric identifier to be used the next time a newHttp2Stream
is created by thisHttp2Session
. -
localWindowSize
<number> 远程对等方在不接收WINDOW_UPDATE
的情况下可以发送的字节数。¥
localWindowSize
<number> The number of bytes that the remote peer can send without receiving aWINDOW_UPDATE
. -
lastProcStreamID
<number> 最近收到HEADERS
或DATA
帧的Http2Stream
的数字 ID。¥
lastProcStreamID
<number> The numeric id of theHttp2Stream
for which aHEADERS
orDATA
frame was most recently received. -
remoteWindowSize
<number> 此Http2Session
在不接收WINDOW_UPDATE
的情况下可以发送的字节数。¥
remoteWindowSize
<number> The number of bytes that thisHttp2Session
may send without receiving aWINDOW_UPDATE
. -
outboundQueueSize
<number> 当前在此Http2Session
的出站队列中的帧数。¥
outboundQueueSize
<number> The number of frames currently within the outbound queue for thisHttp2Session
. -
deflateDynamicTableSize
<number> 出站标头压缩状态表的当前大小(以字节为单位)。¥
deflateDynamicTableSize
<number> The current size in bytes of the outbound header compression state table. -
inflateDynamicTableSize
<number> 入站标头压缩状态表的当前大小(以字节为单位)。¥
inflateDynamicTableSize
<number> The current size in bytes of the inbound header compression state table.
-
描述当前 Http2Session
状态的对象。
¥An object describing the current status of this Http2Session
.
http2session.settings([settings][, callback])
#
-
settings
<HTTP/2 Settings Object> -
callback
<Function> 一旦会话连接或会话已连接时立即调用的回调。¥
callback
<Function> Callback that is called once the session is connected or right away if the session is already connected.-
settings
<HTTP/2 Settings Object> 更新后的settings
对象。¥
settings
<HTTP/2 Settings Object> The updatedsettings
object. -
duration
<integer>
更新此 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
#
如果此 Http2Session
实例是服务器,则 http2session.type
将等于 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
-
¥Extends: <Http2Session>
serverhttp2session.altsvc(alt, originOrStream)
#
-
alt
<string> RFC 7838 定义的替代服务配置的描述。¥
alt
<string> A description of the alternative service configuration as defined by RFC 7838. -
originOrStream
<number> | <string> | <URL> | <Object> 指定来源的 URL 字符串(或具有origin
属性的Object
)或由http2stream.id
属性给出的活动Http2Stream
的数字标识符。¥
originOrStream
<number> | <string> | <URL> | <Object> Either a URL string specifying the origin (or anObject
with anorigin
property) or the numeric identifier of an activeHttp2Stream
as given by thehttp2stream.id
property.
向连接的客户端提交 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
和原始字符串必须仅包含 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 字符串,其中包含与特定主机和端口关联的以逗号分隔的 "alternative" 协议列表。
¥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 协议 ID。
¥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)
#
-
origins
<string> | <URL> | <Object> 一个或多个 URL 字符串作为单独的参数传入。¥
origins
<string> | <URL> | <Object> One or more URL Strings passed as separate arguments.
向连接的客户端提交 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
-
¥Extends: <Http2Session>
事件:'altsvc'
#
¥Event: 'altsvc'
每当客户端接收到 ALTSVC
帧时,则会触发 'altsvc'
事件。事件使用 ALTSVC
值、来源和流 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
<string[]>
每当客户端接收到 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])
#
-
headers
<HTTP/2 Headers Object> -
options
<Object>-
endStream
<boolean>true
如果Http2Stream
可写端最初应关闭,例如发送不应期望有效负载正文的GET
请求时。¥
endStream
<boolean>true
if theHttp2Stream
writable side should be closed initially, such as when sending aGET
request that should not expect a payload body. -
exclusive
<boolean> 当true
和parent
标识父流时,创建的流将成为父流的唯一直接依赖,所有其他现有依赖都成为新创建流的依赖。默认值:false
。¥
exclusive
<boolean> Whentrue
andparent
identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. Default:false
. -
parent
<number> 指定新创建的流所依赖的流的数字标识符。¥
parent
<number> Specifies the numeric identifier of a stream the newly created stream is dependent on. -
weight
<number> 指定流相对于具有相同parent
的其他流的相对依赖。该值为1
到256
(含)之间的数字。¥
weight
<number> Specifies the relative dependency of a stream in relation to other streams with the sameparent
. The value is a number between1
and256
(inclusive). -
waitForTrailers
<boolean> 当为true
时,Http2Stream
将在发送完最后的DATA
帧后触发'wantTrailers'
事件。¥
waitForTrailers
<boolean> Whentrue
, theHttp2Stream
will emit the'wantTrailers'
event after the finalDATA
frame has been sent. -
signal
<AbortSignal> 可用于中止正在进行的请求的中止信号。¥
signal
<AbortSignal> An AbortSignal that may be used to abort an ongoing request.
-
-
¥Returns: <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
,则传输完最后的 DATA
帧时,Http2Stream
不会自动关闭。用户代码必须调用 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
.
当 options.signal
设置为 AbortSignal
,然后调用相应 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
-
¥Extends: <stream.Duplex>
Http2Stream
类的每个实例代表一个通过 Http2Session
实例的双向 HTTP/2 通信流。任何单个 Http2Session
在其生命周期内最多可以有 231-1 个 Http2Stream
实例。
¥Each instance of the Http2Stream
class represents a bidirectional HTTP/2
communications stream over an Http2Session
instance. Any single Http2Session
may have up to 231-1 Http2Stream
instances over its lifetime.
用户代码不会直接构造 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:
-
接收到新的 HTTP/2
HEADERS
帧,其中包含以前未使用的流 ID;¥A new HTTP/2
HEADERS
frame with a previously unused stream ID is received; -
调用了
http2stream.pushStream()
方法。¥The
http2stream.pushStream()
method is called.
在客户端,ClientHttp2Stream
的实例是在调用 http2session.request()
方法时创建的。
¥On the client side, instances of ClientHttp2Stream
are created when the
http2session.request()
method is called.
在客户端,如果父 Http2Session
尚未完全建立,则 http2session.request()
返回的 Http2Stream
实例可能不会立即准备好使用。在这种情况下,在 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
帧,并且(仅对于客户端流)已读取待处理数据。¥An
RST_STREAM
frame for the stream is received by the connected peer, and (for client streams only) pending data has been read. -
调用了
http2stream.close()
方法,并且(仅对于客户端流)已读取待处理数据。¥The
http2stream.close()
method is called, and (for client streams only) pending data has been read. -
调用
http2stream.destroy()
或http2session.destroy()
方法。¥The
http2stream.destroy()
orhttp2session.destroy()
methods are called.
当 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'
每当 Http2Stream
实例在通信中途异常中止时,就会触发 'aborted'
事件。其监听器不需要任何参数。
¥The 'aborted'
event is emitted whenever a Http2Stream
instance is
abnormally aborted in mid-communication.
Its listener does not expect any arguments.
只有在 Http2Stream
可写端尚未结束时才会触发 'aborted'
事件。
¥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.
可以使用 http2stream.rstCode
属性检索关闭流时使用的 HTTP/2 错误代码。如果代码是除 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.
事件:'error'
#
¥Event: 'error'
error
<Error>
'error'
事件在处理 Http2Stream
期间发生错误时触发。
¥The 'error'
event is emitted when an error occurs during the processing of
an Http2Stream
.
事件:'frameError'
#
¥Event: 'frameError'
-
type
<integer> 帧类型。¥
type
<integer> The frame type. -
code
<integer> 错误代码。¥
code
<integer> The error code. -
id
<integer> 流 id(或如果帧不与流相关联,则为0
)。¥
id
<integer> The stream id (or0
if the frame isn't associated with a stream).
当尝试发送帧时发生错误时会触发 'frameError'
事件。当调用时,句柄函数将接收标识帧类型的整数参数和标识错误代码的整数参数。Http2Stream
实例将在 'frameError'
事件触发后立即销毁。
¥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'
在使用 http2stream.setTimeout()
设置的毫秒数内没有收到此 Http2Stream
的活动后,则将触发 'timeout'
事件。其监听器不需要任何参数。
¥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'
-
headers
<HTTP/2 Headers Object> 描述标头的对象¥
headers
<HTTP/2 Headers Object> An object describing the headers -
flags
<number> 相关的数字标志¥
flags
<number> The associated numeric flags
当接收到与尾随标头字段关联的标头块时,则会触发 '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
#
如果 Http2Stream
实例异常中止,则设置为 true
。当设置时,则 'aborted'
事件将被触发。
¥Set to true
if the Http2Stream
instance was aborted abnormally. When set,
the 'aborted'
event will have been emitted.
http2stream.bufferSize
#
此属性显示当前缓冲要写入的字符数。详见 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
).¥
code
<number> Unsigned 32-bit integer identifying the error code. Default:http2.constants.NGHTTP2_NO_ERROR
(0x00
). -
callback
<Function> 注册了可选函数来监听'close'
事件。¥
callback
<Function> An optional function registered to listen for the'close'
event.
通过向连接的 HTTP/2 对等体发送 RST_STREAM
帧来关闭 Http2Stream
实例。
¥Closes the Http2Stream
instance by sending an RST_STREAM
frame to the
connected HTTP/2 peer.
http2stream.closed
#
如果 Http2Stream
实例已关闭,则设置为 true
。
¥Set to true
if the Http2Stream
instance has been closed.
http2stream.destroyed
#
如果 Http2Stream
实例已被销毁且不再可用,则设置为 true
。
¥Set to true
if the Http2Stream
instance has been destroyed and is no longer
usable.
http2stream.endAfterHeaders
#
如果在收到的请求或响应 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
#
此 Http2Stream
实例的数字流标识符如果尚未分配流标识符,则设置为 undefined
。
¥The numeric stream identifier of this Http2Stream
instance. Set to undefined
if the stream identifier has not yet been assigned.
http2stream.pending
#
如果尚未为 Http2Stream
实例分配数字流标识符,则设置为 true
。
¥Set to true
if the Http2Stream
instance has not yet been assigned a
numeric stream identifier.
http2stream.priority(options)
#
-
options
<Object>-
exclusive
<boolean> 当true
和parent
标识父流时,此流将成为父流的唯一直接依赖,所有其他现有依赖都成为此流的依赖。默认值:false
。¥
exclusive
<boolean> Whentrue
andparent
identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. Default:false
. -
parent
<number> 指定此流所依赖的流的数字标识符。¥
parent
<number> Specifies the numeric identifier of a stream this stream is dependent on. -
weight
<number> 指定流相对于具有相同parent
的其他流的相对依赖。该值为1
到256
(含)之间的数字。¥
weight
<number> Specifies the relative dependency of a stream in relation to other streams with the sameparent
. The value is a number between1
and256
(inclusive). -
silent
<boolean> 当为true
时,本地改变优先级,而不向连接的对端发送PRIORITY
帧。¥
silent
<boolean> Whentrue
, changes the priority locally without sending aPRIORITY
frame to the connected peer.
-
更新此 Http2Stream
实例的优先级。
¥Updates the priority for this Http2Stream
instance.
http2stream.rstCode
#
设置为 RST_STREAM
错误码 在从连接的对等方接收到 RST_STREAM
帧、调用 http2stream.close()
或 http2stream.destroy()
后销毁 Http2Stream
时报告。如果 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
#
包含为此 Http2Stream
发送的出站标头的对象。
¥An object containing the outbound headers sent for this Http2Stream
.
http2stream.sentInfoHeaders
#
包含为此 Http2Stream
发送的出站信息(附加)标头的对象数组。
¥An array of objects containing the outbound informational (additional) headers
sent for this Http2Stream
.
http2stream.sentTrailers
#
包含为此 HttpStream
发送的出站尾随标头的对象。
¥An object containing the outbound trailers sent for this HttpStream
.
http2stream.session
#
对拥有此 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
.
-
-
localWindowSize
<number> 连接的对等体可以为此Http2Stream
发送的字节数,而不会收到WINDOW_UPDATE
。¥
localWindowSize
<number> The number of bytes the connected peer may send for thisHttp2Stream
without receiving aWINDOW_UPDATE
. -
state
<number> 指示由nghttp2
确定的Http2Stream
的低层当前状态的标志。¥
state
<number> A flag indicating the low-level current state of theHttp2Stream
as determined bynghttp2
. -
localClose
<number>1
(如果该Http2Stream
已在本地关闭)。¥
localClose
<number>1
if thisHttp2Stream
has been closed locally. -
remoteClose
<number>1
(如果此Http2Stream
已远程关闭)。¥
remoteClose
<number>1
if thisHttp2Stream
has been closed remotely. -
sumDependencyWeight
<number> 使用PRIORITY
帧指定的依赖于此Http2Stream
的所有Http2Stream
实例的总权重。¥
sumDependencyWeight
<number> The sum weight of allHttp2Stream
instances that depend on thisHttp2Stream
as specified usingPRIORITY
frames. -
weight
<number> 此Http2Stream
的优先权重。¥
weight
<number> The priority weight of thisHttp2Stream
.
-
此 Http2Stream
的当前状态。
¥A current state of this Http2Stream
.
http2stream.sendTrailers(headers)
#
headers
<HTTP/2 Headers Object>
向连接的 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
-
¥Extends <Http2Stream>
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'
-
headers
<HTTP/2 Headers Object> -
flags
<number>
当接收到流的附加标头块时,例如接收到 1xx
信息标头块时,则会触发 'headers'
事件。监听器回调传递 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 and flags
associated with the headers.
stream.on('headers', (headers, flags) => {
console.log(headers);
});
事件:'push'
#
¥Event: 'push'
-
headers
<HTTP/2 Headers Object> -
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'
-
headers
<HTTP/2 Headers Object> -
flags
<number>
当从连接的 HTTP/2 服务器收到此流的响应 HEADERS
帧时,则将触发 'response'
事件。使用两个参数调用监听器:包含接收到的 HTTP/2 标头对象 的 Object
,以及与标头关联的标志。
¥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 two arguments: an Object
containing the received
HTTP/2 Headers Object, and flags associated with the 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
-
¥Extends: <Http2Stream>
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)
#
headers
<HTTP/2 Headers Object>
向连接的 HTTP/2 对等方发送额外的信息性 HEADERS
帧。
¥Sends an additional informational HEADERS
frame to the connected HTTP/2 peer.
http2stream.headersSent
#
如果标头被发送则为 true,否则为 false(只读)。
¥True if headers were sent, false otherwise (read-only).
http2stream.pushAllowed
#
只读属性映射到远程客户端最近的 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)
#
-
headers
<HTTP/2 Headers Object> -
options
<Object>-
exclusive
<boolean> 当true
和parent
标识父流时,创建的流将成为父流的唯一直接依赖,所有其他现有依赖都成为新创建流的依赖。默认值:false
。¥
exclusive
<boolean> Whentrue
andparent
identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. Default:false
. -
parent
<number> 指定新创建的流所依赖的流的数字标识符。¥
parent
<number> Specifies the numeric identifier of a stream the newly created stream is dependent on.
-
-
callback
<Function> 推送流启动后调用的回调。¥
callback
<Function> Callback that is called once the push stream has been initiated.-
err
<Error> -
pushStream
<ServerHttp2Stream> 返回的pushStream
对象。¥
pushStream
<ServerHttp2Stream> The returnedpushStream
object. -
headers
<HTTP/2 Headers Object> 用于启动pushStream
的标头对象。¥
headers
<HTTP/2 Headers Object> Headers object thepushStream
was initiated with.
-
启动推送流。使用为作为第二个参数传入的推送流创建的新 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]])
#
-
headers
<HTTP/2 Headers Object> -
options
<Object>-
endStream
<boolean> 设置为true
表示响应将不包含有效负载数据。¥
endStream
<boolean> Set totrue
to indicate that the response will not include payload data. -
waitForTrailers
<boolean> 当为true
时,Http2Stream
将在发送完最后的DATA
帧后触发'wantTrailers'
事件。¥
waitForTrailers
<boolean> Whentrue
, theHttp2Stream
will emit the'wantTrailers'
event after the finalDATA
frame has been sent.
-
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
,则传输完最后的 DATA
帧时,Http2Stream
不会自动关闭。用户代码必须调用 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> 可读的文件描述符。¥
fd
<number> | <FileHandle> A readable file descriptor. -
headers
<HTTP/2 Headers Object> -
options
<Object>-
statCheck
<Function> -
waitForTrailers
<boolean> 当为true
时,Http2Stream
将在发送完最后的DATA
帧后触发'wantTrailers'
事件。¥
waitForTrailers
<boolean> Whentrue
, theHttp2Stream
will emit the'wantTrailers'
event after the finalDATA
frame has been sent. -
offset
<number> 开始读取的偏移位置。¥
offset
<number> The offset position at which to begin reading. -
length
<number> 从文件描述符发送的数据量。¥
length
<number> The amount of data from the fd to send.
-
启动响应,其数据从给定的文件描述符中读取。不对给定的文件描述符进行验证。如果在尝试使用文件描述符读取数据时发生错误,则 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
,则传输完最后的 DATA
帧时,Http2Stream
不会自动关闭。用户代码必须调用 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]])
#
-
headers
<HTTP/2 Headers Object> -
options
<Object>-
statCheck
<Function> -
onError
<Function> 在发送前发生错误时调用的回调函数。¥
onError
<Function> Callback function invoked in the case of an error before send. -
waitForTrailers
<boolean> 当为true
时,Http2Stream
将在发送完最后的DATA
帧后触发'wantTrailers'
事件。¥
waitForTrailers
<boolean> Whentrue
, theHttp2Stream
will emit the'wantTrailers'
event after the finalDATA
frame has been sent. -
offset
<number> 开始读取的偏移位置。¥
offset
<number> The offset position at which to begin reading. -
length
<number> 从文件描述符发送的数据量。¥
length
<number> The amount of data from the fd to send.
-
发送普通文件作为响应。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:
如果在尝试读取文件数据时发生错误,将使用标准 INTERNAL_ERROR
代码使用 RST_STREAM
帧关闭 Http2Stream
。如果定义了 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
来取消发送操作。例如,条件请求可能会检查统计结果以确定文件是否已被修改以返回适当的 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
,则传输完最后的 DATA
帧时,Http2Stream
不会自动关闭。用户代码必须调用 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>
¥Extends: <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> 对流的引用¥
stream
<Http2Stream> A reference to the stream -
headers
<HTTP/2 Headers Object> 描述标头的对象¥
headers
<HTTP/2 Headers Object> An object describing the headers -
flags
<number> 相关的数字标志¥
flags
<number> The associated numeric flags -
rawHeaders
<Array> 包含原始标头名称后跟它们各自值的数组。¥
rawHeaders
<Array> An array containing the raw header names followed by their respective values.
当与服务器关联的 Http2Session
触发 'stream'
事件时,则将触发 'stream'
事件。
¥The 'stream'
event is emitted when a 'stream'
event has been emitted by
an Http2Session
associated with the server.
另见 Http2Session
的 'stream'
事件。
¥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'
当服务器上在使用 http2server.setTimeout()
设置的给定毫秒数内没有活动时,则会触发 'timeout'
事件。默认值: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]()
#
¥Stability: 1 - Experimental
调用 server.close()
并返回一个在服务器关闭时履行的 promise。
¥Calls server.close()
and returns a promise that fulfills when the
server has closed.
server.setTimeout([msecs][, callback])
#
-
msecs
<number> 默认值:0(无超时)¥
msecs
<number> Default: 0 (no timeout) -
callback
<Function> -
¥Returns: <Http2Server>
用于设置 http2 服务器请求的超时值,设置 msecs
毫秒后 Http2Server
上没有活动时调用的回调函数。
¥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
#
假定套接字超时之前不活动的毫秒数。
¥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])
#
settings
<HTTP/2 Settings Object>
用于使用提供的设置更新服务器。
¥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>
¥Extends: <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>
当与 Http2SecureServer
关联的 Http2Session
对象触发 'error'
事件时,则将触发 'sessionError'
事件。
¥The 'sessionError'
event is emitted when an 'error'
event is emitted by
an Http2Session
object associated with the Http2SecureServer
.
事件:'stream'
#
¥Event: 'stream'
-
stream
<Http2Stream> 对流的引用¥
stream
<Http2Stream> A reference to the stream -
headers
<HTTP/2 Headers Object> 描述标头的对象¥
headers
<HTTP/2 Headers Object> An object describing the headers -
flags
<number> 相关的数字标志¥
flags
<number> The associated numeric flags -
rawHeaders
<Array> 包含原始标头名称后跟它们各自值的数组。¥
rawHeaders
<Array> An array containing the raw header names followed by their respective values.
当与服务器关联的 Http2Session
触发 'stream'
事件时,则将触发 'stream'
事件。
¥The 'stream'
event is emitted when a 'stream'
event has been emitted by
an Http2Session
associated with the server.
另见 Http2Session
的 'stream'
事件。
¥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'
当服务器上在使用 http2secureServer.setTimeout()
设置的给定毫秒数内没有活动时,则会触发 'timeout'
事件。默认值: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 扩展或发送不包含 HTTP/2 (h2
) 的 ALPN 扩展,则会触发此事件。较新版本的 Node.js 仅在 allowHTTP1
为 false
且客户端未发送 ALPN 扩展时才会触发此事件。如果客户端发送不包含 HTTP/2(或 HTTP/1.1,如果 allowHTTP1
为 true
)的 ALPN 扩展,则 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 分钟)¥
msecs
<number> Default:120000
(2 minutes) -
callback
<Function> -
¥Returns: <Http2SecureServer>
用于设置 http2 安全服务器请求的超时值,设置 msecs
毫秒后 Http2SecureServer
上没有活动时调用的回调函数。
¥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
#
假定套接字超时之前不活动的毫秒数。
¥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])
#
settings
<HTTP/2 Settings Object>
用于使用提供的设置更新服务器。
¥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
。¥
maxDeflateDynamicTableSize
<number> Sets the maximum dynamic table size for deflating header fields. Default:4Kib
. -
maxSettings
<number> 设置每SETTINGS
帧的最大设置条目数。允许的最小值为1
。默认值:32
。¥
maxSettings
<number> Sets the maximum number of settings entries perSETTINGS
frame. The minimum value allowed is1
. Default:32
. -
maxSessionMemory
<number> 设置允许Http2Session
使用的最大内存。该值以兆字节数表示,例如1
等于 1 兆字节。允许的最小值为1
。这是一个基于信用的限制,现有的Http2Stream
可能会导致超过此限制,但新的Http2Stream
实例将在超过此限制时被拒绝。当前Http2Stream
会话数、标头压缩表的当前内存使用、当前排队等待发送的数据以及未确认的PING
和SETTINGS
帧都计入当前限制。默认值:10
。¥
maxSessionMemory
<number> Sets the maximum memory that theHttp2Session
is permitted to use. The value is expressed in terms of number of megabytes, e.g.1
equal 1 megabyte. The minimum value allowed is1
. This is a credit based limit, existingHttp2Stream
s may cause this limit to be exceeded, but newHttp2Stream
instances will be rejected while this limit is exceeded. The current number ofHttp2Stream
sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledgedPING
andSETTINGS
frames are all counted towards the current limit. Default:10
. -
maxHeaderListPairs
<number> 设置标头条目的最大数量。这类似于node:http
模块中的server.maxHeadersCount
或request.maxHeadersCount
。最小值为4
。默认值:128
。¥
maxHeaderListPairs
<number> Sets the maximum number of header entries. This is similar toserver.maxHeadersCount
orrequest.maxHeadersCount
in thenode:http
module. The minimum value is4
. Default:128
. -
maxOutstandingPings
<number> 设置未确认的未确认 ping 的最大数量。默认值:10
。¥
maxOutstandingPings
<number> Sets the maximum number of outstanding, unacknowledged pings. Default:10
. -
maxSendHeaderBlockLength
<number> 设置序列化的、压缩的标头块的最大允许大小。尝试发送超出此限制的标头将导致触发'frameError'
事件并且流被关闭和销毁。虽然这将最大允许大小设置为整个标头块,但nghttp2
(内部 http2 库)对每个解压缩的键/值对都有65536
的限制。¥
maxSendHeaderBlockLength
<number> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a'frameError'
event being emitted and the stream being closed and destroyed. While this sets the maximum allowed size to the entire block of headers,nghttp2
(the internal http2 library) has a limit of65536
for each decompressed key/value pair. -
paddingStrategy
<number> 用于确定用于HEADERS
和DATA
帧的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE
。值可能是以下之一:¥
paddingStrategy
<number> The strategy used for determining the amount of padding to use forHEADERS
andDATA
frames. Default:http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:-
http2.constants.PADDING_STRATEGY_NONE
:没有应用填充。¥
http2.constants.PADDING_STRATEGY_NONE
: No padding is applied. -
http2.constants.PADDING_STRATEGY_MAX
:应用由内部实现决定的最大填充量。¥
http2.constants.PADDING_STRATEGY_MAX
: The maximum amount of padding, determined by the internal implementation, is applied. -
http2.constants.PADDING_STRATEGY_ALIGNED
:尝试应用足够的填充以确保包括 9 字节标头在内的总帧长度是 8 的倍数。对于每一帧,有一个由当前流控制状态和设置决定的最大允许填充字节数。如果此最大值小于确保对齐所需的计算量,则使用最大值,并且总帧长度不一定按 8 字节对齐。¥
http2.constants.PADDING_STRATEGY_ALIGNED
: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.
-
-
peerMaxConcurrentStreams
<number> 设置远程对等方的最大并发流数,就好像已收到SETTINGS
帧一样。如果远程对等方为maxConcurrentStreams
设置了自己的值,则将被覆盖。默认值:100
。¥
peerMaxConcurrentStreams
<number> Sets the maximum number of concurrent streams for the remote peer as if aSETTINGS
frame had been received. Will be overridden if the remote peer sets its own value formaxConcurrentStreams
. Default:100
. -
maxSessionInvalidFrames
<integer> 设置会话关闭前允许的最大无效帧数。默认值:1000
。¥
maxSessionInvalidFrames
<integer> Sets the maximum number of invalid frames that will be tolerated before the session is closed. Default:1000
. -
maxSessionRejectedStreams
<integer> 设置会话关闭前允许的创建流拒绝的最大数量。每个拒绝都与NGHTTP2_ENHANCE_YOUR_CALM
错误相关联,该错误应该告诉对等方不要再打开任何流,因此继续打开流被视为行为不端的对等方的标志。默认值:100
。¥
maxSessionRejectedStreams
<integer> Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with anNGHTTP2_ENHANCE_YOUR_CALM
error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. Default:100
. -
settings
<HTTP/2 Settings Object> 连接时发送到远程对等方的初始设置。¥
settings
<HTTP/2 Settings Object> The initial settings to send to the remote peer upon connection. -
streamResetBurst
<number> 并且streamResetRate
<number> 设置传入流重置(RST_STREAM 帧)的速率限制。必须设置这两个设置才能生效,默认值分别为 1000 和 33。¥
streamResetBurst
<number> andstreamResetRate
<number> Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively. -
remoteCustomSettings
<Array> 整数值数组确定设置类型,这些类型包含在接收到的远程设置的CustomSettings
属性中。有关允许的设置类型的更多信息,请参阅Http2Settings
对象的CustomSettings
属性。¥
remoteCustomSettings
<Array> The array of integer values determines the settings types, which are included in theCustomSettings
-property of the received remoteSettings. Please see theCustomSettings
-property of theHttp2Settings
object for more information, on the allowed setting types. -
Http1IncomingMessage
<http.IncomingMessage> 指定用于 HTTP/1 回退的IncomingMessage
类。用于扩展原始的http.IncomingMessage
。默认值:http.IncomingMessage
。¥
Http1IncomingMessage
<http.IncomingMessage> Specifies theIncomingMessage
class to used for HTTP/1 fallback. Useful for extending the originalhttp.IncomingMessage
. Default:http.IncomingMessage
. -
Http1ServerResponse
<http.ServerResponse> 指定用于 HTTP/1 回退的ServerResponse
类。用于扩展原始的http.ServerResponse
。默认值:http.ServerResponse
。¥
Http1ServerResponse
<http.ServerResponse> Specifies theServerResponse
class to used for HTTP/1 fallback. Useful for extending the originalhttp.ServerResponse
. Default:http.ServerResponse
. -
Http2ServerRequest
<http2.Http2ServerRequest> 指定要使用的Http2ServerRequest
类。用于扩展原始的Http2ServerRequest
。默认值:Http2ServerRequest
。¥
Http2ServerRequest
<http2.Http2ServerRequest> Specifies theHttp2ServerRequest
class to use. Useful for extending the originalHttp2ServerRequest
. Default:Http2ServerRequest
. -
Http2ServerResponse
<http2.Http2ServerResponse> 指定要使用的Http2ServerResponse
类。用于扩展原始的Http2ServerResponse
。默认值:Http2ServerResponse
。¥
Http2ServerResponse
<http2.Http2ServerResponse> Specifies theHttp2ServerResponse
class to use. Useful for extending the originalHttp2ServerResponse
. Default:Http2ServerResponse
. -
unknownProtocolTimeout
<number> 指定在触发'unknownProtocol'
时服务器应等待的超时(以毫秒为单位)。如果到那时套接字还没有被销毁,则服务器将销毁它。默认值:10000
。¥
unknownProtocolTimeout
<number> Specifies a timeout in milliseconds that a server should wait when an'unknownProtocol'
is emitted. If the socket has not been destroyed by that time the server will destroy it. Default:10000
. -
...:可以提供任何
net.createServer()
选项。¥...: Any
net.createServer()
option can be provided.
-
-
onRequestHandler
<Function> 参见 兼容性接口¥
onRequestHandler
<Function> See Compatibility API -
¥Returns: <Http2Server>
返回创建和管理 Http2Session
实例的 net.Server
实例。
¥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
。¥
allowHTTP1
<boolean> Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set totrue
. See the'unknownProtocol'
event. See ALPN negotiation. Default:false
. -
maxDeflateDynamicTableSize
<number> 设置用于压缩标头字段的最大动态表大小。默认值:4Kib
。¥
maxDeflateDynamicTableSize
<number> Sets the maximum dynamic table size for deflating header fields. Default:4Kib
. -
maxSettings
<number> 设置每SETTINGS
帧的最大设置条目数。允许的最小值为1
。默认值:32
。¥
maxSettings
<number> Sets the maximum number of settings entries perSETTINGS
frame. The minimum value allowed is1
. Default:32
. -
maxSessionMemory
<number> 设置允许Http2Session
使用的最大内存。该值以兆字节数表示,例如1
等于 1 兆字节。允许的最小值为1
。这是一个基于信用的限制,现有的Http2Stream
可能会导致超过此限制,但新的Http2Stream
实例将在超过此限制时被拒绝。当前Http2Stream
会话数、标头压缩表的当前内存使用、当前排队等待发送的数据以及未确认的PING
和SETTINGS
帧都计入当前限制。默认值:10
。¥
maxSessionMemory
<number> Sets the maximum memory that theHttp2Session
is permitted to use. The value is expressed in terms of number of megabytes, e.g.1
equal 1 megabyte. The minimum value allowed is1
. This is a credit based limit, existingHttp2Stream
s may cause this limit to be exceeded, but newHttp2Stream
instances will be rejected while this limit is exceeded. The current number ofHttp2Stream
sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledgedPING
andSETTINGS
frames are all counted towards the current limit. Default:10
. -
maxHeaderListPairs
<number> 设置标头条目的最大数量。这类似于node:http
模块中的server.maxHeadersCount
或request.maxHeadersCount
。最小值为4
。默认值:128
。¥
maxHeaderListPairs
<number> Sets the maximum number of header entries. This is similar toserver.maxHeadersCount
orrequest.maxHeadersCount
in thenode:http
module. The minimum value is4
. Default:128
. -
maxOutstandingPings
<number> 设置未确认的未确认 ping 的最大数量。默认值:10
。¥
maxOutstandingPings
<number> Sets the maximum number of outstanding, unacknowledged pings. Default:10
. -
maxSendHeaderBlockLength
<number> 设置序列化的、压缩的标头块的最大允许大小。尝试发送超出此限制的标头将导致触发'frameError'
事件并且流被关闭和销毁。¥
maxSendHeaderBlockLength
<number> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a'frameError'
event being emitted and the stream being closed and destroyed. -
paddingStrategy
<number> 用于确定用于HEADERS
和DATA
帧的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE
。值可能是以下之一:¥
paddingStrategy
<number> Strategy used for determining the amount of padding to use forHEADERS
andDATA
frames. Default:http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:-
http2.constants.PADDING_STRATEGY_NONE
:没有应用填充。¥
http2.constants.PADDING_STRATEGY_NONE
: No padding is applied. -
http2.constants.PADDING_STRATEGY_MAX
:应用由内部实现决定的最大填充量。¥
http2.constants.PADDING_STRATEGY_MAX
: The maximum amount of padding, determined by the internal implementation, is applied. -
http2.constants.PADDING_STRATEGY_ALIGNED
:尝试应用足够的填充以确保包括 9 字节标头在内的总帧长度是 8 的倍数。对于每一帧,有一个由当前流控制状态和设置决定的最大允许填充字节数。如果此最大值小于确保对齐所需的计算量,则使用最大值,并且总帧长度不一定按 8 字节对齐。¥
http2.constants.PADDING_STRATEGY_ALIGNED
: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.
-
-
peerMaxConcurrentStreams
<number> 设置远程对等方的最大并发流数,就好像已收到SETTINGS
帧一样。如果远程对等方为maxConcurrentStreams
设置了自己的值,则将被覆盖。默认值:100
。¥
peerMaxConcurrentStreams
<number> Sets the maximum number of concurrent streams for the remote peer as if aSETTINGS
frame had been received. Will be overridden if the remote peer sets its own value formaxConcurrentStreams
. Default:100
. -
maxSessionInvalidFrames
<integer> 设置会话关闭前允许的最大无效帧数。默认值:1000
。¥
maxSessionInvalidFrames
<integer> Sets the maximum number of invalid frames that will be tolerated before the session is closed. Default:1000
. -
maxSessionRejectedStreams
<integer> 设置会话关闭前允许的创建流拒绝的最大数量。每个拒绝都与NGHTTP2_ENHANCE_YOUR_CALM
错误相关联,该错误应该告诉对等方不要再打开任何流,因此继续打开流被视为行为不端的对等方的标志。默认值:100
。¥
maxSessionRejectedStreams
<integer> Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with anNGHTTP2_ENHANCE_YOUR_CALM
error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. Default:100
. -
settings
<HTTP/2 Settings Object> 连接时发送到远程对等方的初始设置。¥
settings
<HTTP/2 Settings Object> The initial settings to send to the remote peer upon connection. -
remoteCustomSettings
<Array> 整数值数组确定设置类型,这些类型包含在接收到的远程设置的customSettings
属性中。有关允许的设置类型的更多信息,请参阅Http2Settings
对象的customSettings
属性。¥
remoteCustomSettings
<Array> The array of integer values determines the settings types, which are included in thecustomSettings
-property of the received remoteSettings. Please see thecustomSettings
-property of theHttp2Settings
object for more information, on the allowed setting types. -
...:可以提供任何
tls.createServer()
选项。对于服务器,通常需要身份选项(pfx
或key
/cert
)。¥...: Any
tls.createServer()
options can be provided. For servers, the identity options (pfx
orkey
/cert
) are usually required. -
origins
<string[]> 在创建新服务器Http2Session
后立即在ORIGIN
帧内发送的原始字符串数组。¥
origins
<string[]> An array of origin strings to send within anORIGIN
frame immediately following creation of a new serverHttp2Session
. -
unknownProtocolTimeout
<number> 指定在触发'unknownProtocol'
事件时服务器应等待的超时(以毫秒为单位)。如果到那时套接字还没有被销毁,则服务器将销毁它。默认值:10000
。¥
unknownProtocolTimeout
<number> Specifies a timeout in milliseconds that a server should wait when an'unknownProtocol'
event is emitted. If the socket has not been destroyed by that time the server will destroy it. Default:10000
.
-
-
onRequestHandler
<Function> 参见 兼容性接口¥
onRequestHandler
<Function> See Compatibility API -
¥Returns: <Http2SecureServer>
返回创建和管理 Http2Session
实例的 tls.Server
实例。
¥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 服务器。这必须是带有http://
或https://
前缀、主机名和 IP 端口(如果使用非默认端口)的最小有效 URL 的形式。URL 中的用户信息(用户 ID 和密码)、路径、查询字符串和片段详细信息将被忽略。¥
authority
<string> | <URL> The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with thehttp://
orhttps://
prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. -
options
<Object>-
maxDeflateDynamicTableSize
<number> 设置用于压缩标头字段的最大动态表大小。默认值:4Kib
。¥
maxDeflateDynamicTableSize
<number> Sets the maximum dynamic table size for deflating header fields. Default:4Kib
. -
maxSettings
<number> 设置每SETTINGS
帧的最大设置条目数。允许的最小值为1
。默认值:32
。¥
maxSettings
<number> Sets the maximum number of settings entries perSETTINGS
frame. The minimum value allowed is1
. Default:32
. -
maxSessionMemory
<number> 设置允许Http2Session
使用的最大内存。该值以兆字节数表示,例如1
等于 1 兆字节。允许的最小值为1
。这是一个基于信用的限制,现有的Http2Stream
可能会导致超过此限制,但新的Http2Stream
实例将在超过此限制时被拒绝。当前Http2Stream
会话数、标头压缩表的当前内存使用、当前排队等待发送的数据以及未确认的PING
和SETTINGS
帧都计入当前限制。默认值:10
。¥
maxSessionMemory
<number> Sets the maximum memory that theHttp2Session
is permitted to use. The value is expressed in terms of number of megabytes, e.g.1
equal 1 megabyte. The minimum value allowed is1
. This is a credit based limit, existingHttp2Stream
s may cause this limit to be exceeded, but newHttp2Stream
instances will be rejected while this limit is exceeded. The current number ofHttp2Stream
sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledgedPING
andSETTINGS
frames are all counted towards the current limit. Default:10
. -
maxHeaderListPairs
<number> 设置标头条目的最大数量。这类似于node:http
模块中的server.maxHeadersCount
或request.maxHeadersCount
。最小值为1
。默认值:128
。¥
maxHeaderListPairs
<number> Sets the maximum number of header entries. This is similar toserver.maxHeadersCount
orrequest.maxHeadersCount
in thenode:http
module. The minimum value is1
. Default:128
. -
maxOutstandingPings
<number> 设置未确认的未确认 ping 的最大数量。默认值:10
。¥
maxOutstandingPings
<number> Sets the maximum number of outstanding, unacknowledged pings. Default:10
. -
maxReservedRemoteStreams
<number> 设置客户端在任何给定时间将接受的最大保留推送流数。一旦当前预留的推送流数量超过此限制,则服务器发送的新推送流将被自动拒绝。最小允许值为 0。允许的最大值为 232-1。负值将此选项设置为最大允许值。默认值:200
。¥
maxReservedRemoteStreams
<number> Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value. Default:200
. -
maxSendHeaderBlockLength
<number> 设置序列化的、压缩的标头块的最大允许大小。尝试发送超出此限制的标头将导致触发'frameError'
事件并且流被关闭和销毁。¥
maxSendHeaderBlockLength
<number> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a'frameError'
event being emitted and the stream being closed and destroyed. -
paddingStrategy
<number> 用于确定用于HEADERS
和DATA
帧的填充量的策略。默认值:http2.constants.PADDING_STRATEGY_NONE
。值可能是以下之一:¥
paddingStrategy
<number> Strategy used for determining the amount of padding to use forHEADERS
andDATA
frames. Default:http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:-
http2.constants.PADDING_STRATEGY_NONE
:没有应用填充。¥
http2.constants.PADDING_STRATEGY_NONE
: No padding is applied. -
http2.constants.PADDING_STRATEGY_MAX
:应用由内部实现决定的最大填充量。¥
http2.constants.PADDING_STRATEGY_MAX
: The maximum amount of padding, determined by the internal implementation, is applied. -
http2.constants.PADDING_STRATEGY_ALIGNED
:尝试应用足够的填充以确保包括 9 字节标头在内的总帧长度是 8 的倍数。对于每一帧,有一个由当前流控制状态和设置决定的最大允许填充字节数。如果此最大值小于确保对齐所需的计算量,则使用最大值,并且总帧长度不一定按 8 字节对齐。¥
http2.constants.PADDING_STRATEGY_ALIGNED
: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.
-
-
peerMaxConcurrentStreams
<number> 设置远程对等方的最大并发流数,就好像已收到SETTINGS
帧一样。如果远程对等方为maxConcurrentStreams
设置了自己的值,则将被覆盖。默认值:100
。¥
peerMaxConcurrentStreams
<number> Sets the maximum number of concurrent streams for the remote peer as if aSETTINGS
frame had been received. Will be overridden if the remote peer sets its own value formaxConcurrentStreams
. Default:100
. -
protocol
<string> 要连接的协议,如果在authority
中没有设置。值可以是'http:'
或'https:'
。默认值:'https:'
¥
protocol
<string> The protocol to connect with, if not set in theauthority
. Value may be either'http:'
or'https:'
. Default:'https:'
-
settings
<HTTP/2 Settings Object> 连接时发送到远程对等方的初始设置。¥
settings
<HTTP/2 Settings Object> The initial settings to send to the remote peer upon connection. -
remoteCustomSettings
<Array> 整数值数组确定设置类型,这些类型包含在接收到的远程设置的CustomSettings
属性中。有关允许的设置类型的更多信息,请参阅Http2Settings
对象的CustomSettings
属性。¥
remoteCustomSettings
<Array> The array of integer values determines the settings types, which are included in theCustomSettings
-property of the received remoteSettings. Please see theCustomSettings
-property of theHttp2Settings
object for more information, on the allowed setting types. -
createConnection
<Function> 可选的回调,它接收传给connect
和options
对象的URL
实例,并返回将用作此会话连接的任何Duplex
流。¥
createConnection
<Function> An optional callback that receives theURL
instance passed toconnect
and theoptions
object, and returns anyDuplex
stream that is to be used as the connection for this session. -
...:可以提供任何
net.connect()
或tls.connect()
选项。¥...: Any
net.connect()
ortls.connect()
options can be provided. -
unknownProtocolTimeout
<number> 指定在触发'unknownProtocol'
事件时服务器应等待的超时(以毫秒为单位)。如果到那时套接字还没有被销毁,则服务器将销毁它。默认值:10000
。¥
unknownProtocolTimeout
<number> Specifies a timeout in milliseconds that a server should wait when an'unknownProtocol'
event is emitted. If the socket has not been destroyed by that time the server will destroy it. Default:10000
.
-
-
listener
<Function> 将注册为'connect'
事件的单次监听器。¥
listener
<Function> Will be registered as a one-time listener of the'connect'
event. -
¥Returns: <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()
#
-
¥Returns: <HTTP/2 Settings Object>
返回包含 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])
#
-
settings
<HTTP/2 Settings Object> -
返回:<Buffer>
¥Returns: <Buffer>
返回一个 Buffer
实例,其中包含 HTTP/2 规范中指定的给定 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: AAIAAAAA
const http2 = require('node:http2');
const packed = http2.getPackedSettings({ enablePush: false });
console.log(packed.toString('base64'));
// Prints: AAIAAAAA
http2.getUnpackedSettings(buf)
#
-
buf
<Buffer> | <TypedArray> 打包的设置。¥
buf
<Buffer> | <TypedArray> The packed settings. -
¥Returns: <HTTP/2 Settings Object>
返回 HTTP/2 设置对象,其中包含由 http2.getPackedSettings()
生成的给定 Buffer
的反序列化设置。
¥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()
选项。¥...: Any
http2.createServer()
option can be provided.
-
-
¥Returns: <ServerHttp2Session>
从现有套接字创建 HTTP/2 服务器会话。
¥Create an HTTP/2 server session from an existing socket.
http2.sensitiveHeaders
#
可以将此符号设置为 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 对象上表示为自有的属性。属性键将被序列化为小写。属性值应该是字符串(如果不是,它们将被强制转换为字符串)或 Array
个字符串(以便为每个标头字段发送一个以上的值)。
¥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
原型。这意味着 Object.prototype.toString()
和 Object.prototype.hasOwnProperty()
等普通 JavaScript 对象方法将不起作用。
¥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
。¥The
:status
header is converted tonumber
. -
: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
被丢弃。¥Duplicates of
: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
orx-content-type-options
are discarded. -
set-cookie
始终是数组。重复项被添加到数组中。¥
set-cookie
is always an array. Duplicates are added to the array. -
对于重复的
cookie
标头,这些值用 '; 连接在一起'.¥For duplicate
cookie
headers, the values are joined together with '; '. -
对于所有其他标头,值使用 ',' 连接。
¥For all other headers, the values are joined together with ', '.
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);
});
敏感标头#
¥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.
设置对象#
¥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
。¥
headerTableSize
<number> Specifies the maximum number of bytes used for header compression. The minimum allowed value is 0. The maximum allowed value is 232-1. Default:4096
. -
enablePush
<boolean> 如果在Http2Session
实例上允许 HTTP/2 推送流,则指定true
。默认值:true
。¥
enablePush
<boolean> Specifiestrue
if HTTP/2 Push Streams are to be permitted on theHttp2Session
instances. Default:true
. -
initialWindowSize
<number> 为流级流量控制指定发送方的初始窗口大小(以字节为单位)。最小允许值为 0。允许的最大值为 232-1。默认值:65535
。¥
initialWindowSize
<number> Specifies the sender's initial window size in bytes for stream-level flow control. The minimum allowed value is 0. The maximum allowed value is 232-1. Default:65535
. -
maxFrameSize
<number> 指定最大帧有效载荷的字节大小。最小允许值为 16,384。允许的最大值为 224-1。默认值:16384
。¥
maxFrameSize
<number> Specifies the size in bytes of the largest frame payload. The minimum allowed value is 16,384. The maximum allowed value is 224-1. Default:16384
. -
maxConcurrentStreams
<number> 指定Http2Session
上允许的最大并发流数。没有默认值,这意味着至少在理论上,在Http2Session
中的任何给定时间可以同时打开 232-1 个流。最小值为 0。允许的最大值为 232-1。默认值:4294967295
。¥
maxConcurrentStreams
<number> Specifies the maximum number of concurrent streams permitted on anHttp2Session
. There is no default value which implies, at least theoretically, 232-1 streams may be open concurrently at any given time in anHttp2Session
. The minimum value is 0. The maximum allowed value is 232-1. Default:4294967295
. -
maxHeaderListSize
<number> 指定将被接受的标头列表的最大大小(未压缩的八位字节)。最小允许值为 0。允许的最大值为 232-1。默认值:65535
。¥
maxHeaderListSize
<number> Specifies the maximum size (uncompressed octets) of header list that will be accepted. The minimum allowed value is 0. The maximum allowed value is 232-1. Default:65535
. -
maxHeaderSize
<number>maxHeaderListSize
的别名。¥
maxHeaderSize
<number> Alias formaxHeaderListSize
. -
enableConnectProtocol
<boolean> 如果要启用 RFC 8441 定义的 "扩展连接协议",则指定true
。此设置仅在服务器发送时才有意义。一旦为给定的Http2Session
启用了enableConnectProtocol
设置,就无法禁用它。默认值:false
。¥
enableConnectProtocol
<boolean> Specifiestrue
if the "Extended Connect Protocol" defined by RFC 8441 is to be enabled. This setting is only meaningful if sent by the server. Once theenableConnectProtocol
setting has been enabled for a givenHttp2Session
, it cannot be disabled. Default:false
. -
customSettings
<Object> 指定其他设置,但尚未在节点和底层库中实现。对象的键定义设置类型的数值(如 [RFC 7540] 建立的 "HTTP/2 SETTINGS" 注册表中所定义)以及设置的实际数值。设置类型必须是 1 到 2^16-1 范围内的整数。它不应该是节点已经处理的设置类型,即当前它应该大于 6,尽管它不是错误。这些值必须是 0 到 2^32-1 范围内的无符号整数。目前最多支持 10 个自定义设置。仅支持发送设置,或接收服务器或客户端对象的remoteCustomSettings
选项中指定的设置值。不要将设置 id 的customSettings
机制与原生处理的设置的接口混合在一起,以防将来的节点版本原生支持某个设置。¥
customSettings
<Object> Specifies additional settings, yet not implemented in node and the underlying libraries. The key of the object defines the numeric value of the settings type (as defined in the "HTTP/2 SETTINGS" registry established by [RFC 7540]) and the values the actual numeric value of the settings. The settings type has to be an integer in the range from 1 to 2^16-1. It should not be a settings type already handled by node, i.e. currently it should be greater than 6, although it is not an error. The values need to be unsigned integers in the range from 0 to 2^32-1. Currently, a maximum of up 10 custom settings is supported. It is only supported for sending SETTINGS, or for receiving settings values specified in theremoteCustomSettings
options of the server or client object. Do not mix thecustomSettings
-mechanism for a settings id with interfaces for the natively handled settings, in case a setting becomes natively supported in a future node version.
设置对象上的所有附加属性都将被忽略。
¥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/1 实现更严格地处理 HTTP 标头名称和值中的无效字符。
¥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 规范的要求,标头字段值的处理更为宽松,但不应包含换行符或回车符,并且应限于 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 定义了 HTTP/2 的 "扩展连接协议" 扩展,可用于使用 CONNECT
方法引导使用 Http2Stream
作为其他通信协议(例如 WebSockets)的隧道。
¥RFC 8441 defines an "Extended CONNECT Protocol" extension to HTTP/2 that
may be used to bootstrap the use of an Http2Stream
using the CONNECT
method as a tunnel for other communication protocols (such as WebSockets).
扩展连接协议的使用由 HTTP/2 服务器通过使用 enableConnectProtocol
设置启用:
¥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 });
一旦客户端从服务器收到指示可以使用扩展 CONNECT 的 SETTINGS
帧,它可能会发送使用 ':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
Compatibility 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
-
¥Extends: <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.
只有在 Http2ServerRequest
可写端尚未结束时才会触发 'aborted'
事件。
¥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
#
如果请求已中止,则 request.aborted
属性将为 true
。
¥The request.aborted
property will be true
if the request has
been aborted.
request.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
#
如果请求已完成、中止或销毁,则 request.complete
属性将为 true
。
¥The request.complete
property will be true
if the request has
been completed, aborted, or destroyed.
request.connection
#
参见 request.socket
。
¥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
#
请求/响应头对象。
¥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
#
在服务器请求的情况下,客户端发送的 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
#
请求方法作为字符串。只读。示例:'GET'
, 'DELETE'
.
¥The request method as a string. Read-only. Examples: 'GET'
, 'DELETE'
.
request.rawHeaders
#
原始请求/响应头完全按照收到的方式列出。
¥The raw request/response headers list exactly as they were received.
键和值在同一个列表中。它不是元组列表。因此,偶数偏移是键值,奇数偏移是关联的值。
¥The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.
标头名称不小写,重复项不合并。
¥Header names are not lowercased, and duplicates are not merged.
// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*/*' ]
console.log(request.rawHeaders);
request.rawTrailers
#
原始请求/响应尾标的键和值与收到的完全一样。仅在 'end'
事件中填充。
¥The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end'
event.
request.scheme
#
请求协议伪标头域,指示目标 URL 的协议部分。
¥The request scheme pseudo header field indicating the scheme portion of the target URL.
request.setTimeout(msecs, callback)
#
-
msecs
<number> -
callback
<Function> -
¥Returns: <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'
监听器,则 Http2Stream
在超时时被销毁。如果将句柄分配给请求、响应或服务器的 'timeout'
事件,则必须显式处理超时套接字。
¥If no 'timeout'
listener is added to the request, the response, or
the server, then Http2Stream
s 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
#
返回 Proxy
对象,该对象充当 net.Socket
(或 tls.TLSSocket
),但应用了基于 HTTP/2 逻辑的获取器、设置器、以及方法。
¥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
检索并设置。
¥destroyed
, readable
, and writable
properties will be retrieved from and
set on request.stream
.
destroy
, emit
, end
, on
和 once
方法将在 request.stream
上调用。
¥destroy
, emit
, end
, on
and once
methods will be called on
request.stream
.
setTimeout
方法将在 request.stream.session
上调用。
¥setTimeout
method will be called on request.stream.session
.
pause
, read
, resume
, and write
将抛出错误代码为 ERR_HTTP2_NO_SOCKET_MANIPULATION
。有关详细信息,请参阅 Http2Session
和套接字。
¥pause
, read
, resume
, and write
will throw an error with code
ERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session
and Sockets for
more information.
所有其他交互将直接路由到套接字。支持 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
对象。
¥The Http2Stream
object backing the request.
request.trailers
#
请求/响应尾标对象。仅在 'end'
事件中填充。
¥The request/response trailers object. Only populated at the 'end'
event.
request.url
#
请求的网址字符串。这仅包含实际 HTTP 请求中存在的网址。如果请求是:
¥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
此对象由 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'
表示底层的 Http2Stream
在 response.end()
被调用或能够刷新之前终止。
¥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
<string> | <string[]>
将单个标头值附加到标头对象。
¥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
。
¥See response.socket
.
response.createPushResponse(headers, callback)
#
-
headers
<HTTP/2 Headers Object> 描述标头的对象¥
headers
<HTTP/2 Headers Object> An object describing the headers -
callback
<Function> 在http2stream.pushStream()
完成后调用,或者在尝试创建推送的Http2Stream
失败或被拒绝时调用,或者在调用http2stream.pushStream()
方法之前关闭Http2ServerRequest
的状态¥
callback
<Function> Called oncehttp2stream.pushStream()
is finished, or either when the attempt to create the pushedHttp2Stream
has failed or has been rejected, or the state ofHttp2ServerRequest
is closed prior to calling thehttp2stream.pushStream()
method-
err
<Error> -
res
<http2.Http2ServerResponse> 新创建的Http2ServerResponse
对象¥
res
<http2.Http2ServerResponse> The newly-createdHttp2ServerResponse
object
-
使用给定的标头调用 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>
¥Returns: <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
#
指示响应是否已完成的布尔值。从 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: <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()
#
返回当前传出标头的浅拷贝。由于使用了浅拷贝,因此无需额外调用各种与标头相关的 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
。这意味着 obj.toString()
、obj.hasOwnProperty()
等典型的 Object
方法没有定义,将不起作用。
¥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
#
如果标头被发送则为 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
#
如果为真,则 Date 标头将自动生成并在响应中发送,如果它尚未出现在标头中。默认为真。
¥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
<string> | <string[]>
为隐式标头设置单个标头值。如果该标头已经存在于待发送的标头中,则其值将被替换。在此处使用字符串数组发送具有相同名称的多个标头。
¥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>
¥Returns: <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'
监听器,则 Http2Stream
在超时时被销毁。如果将句柄分配给请求、响应或服务器的 'timeout'
事件,则必须显式处理超时套接字。
¥If no 'timeout'
listener is added to the request, the response, or
the server, then Http2Stream
s 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
#
返回 Proxy
对象,该对象充当 net.Socket
(或 tls.TLSSocket
),但应用了基于 HTTP/2 逻辑的获取器、设置器、以及方法。
¥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
检索并设置。
¥destroyed
, readable
, and writable
properties will be retrieved from and
set on response.stream
.
destroy
, emit
, end
, on
和 once
方法将在 response.stream
上调用。
¥destroy
, emit
, end
, on
and once
methods will be called on
response.stream
.
setTimeout
方法将在 response.stream.session
上调用。
¥setTimeout
method will be called on response.stream.session
.
pause
, read
, resume
, and write
将抛出错误代码为 ERR_HTTP2_NO_SOCKET_MANIPULATION
。有关详细信息,请参阅 Http2Session
和套接字。
¥pause
, read
, resume
, and write
will throw an error with code
ERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session
and Sockets for
more information.
所有其他交互将直接路由到套接字。
¥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
#
使用隐式标头(不显式调用 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
#
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
对象。
¥The Http2Stream
object backing the response.
response.writableEnded
#
在调用 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>
¥Returns: <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
。
¥chunk
can be a string or a buffer. If chunk
is a string,
the second parameter specifies how to encode it into a byte stream.
By default the encoding
is 'utf8'
. callback
will be called when this chunk
of data is flushed.
这是原始的 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>
向客户端发送带有 Link 标头的状态 103 Early Hints
,表示用户代理可以预加载/预连接链接的资源。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.
示例
¥Example
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> -
返回:<http2.Http2ServerResponse>
¥Returns: <http2.Http2ServerResponse>
向请求发送响应头。状态码是 3 位的 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 和正在传输的正文的长度是否相等。但是,在接收消息时,Node.js 会在 Content-Length
与实际负载大小不匹配时自动拒绝消息。
¥Content-Length
is given in bytes not characters. The
Buffer.byteLength()
API may be used to determine the number of bytes in a
given encoding. On outbound messages, Node.js does not check if Content-Length
and the length of the body being transmitted are equal or not. However, when
receiving messages, Node.js will automatically reject messages when the
Content-Length
does not match the actual payload size.
在调用 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
帧字节数。¥
bytesRead
<number> The number ofDATA
frame bytes received for thisHttp2Stream
. -
bytesWritten
<number> 为此Http2Stream
发送的DATA
帧字节数。¥
bytesWritten
<number> The number ofDATA
frame bytes sent for thisHttp2Stream
. -
id
<number> 关联Http2Stream
的标识符¥
id
<number> The identifier of the associatedHttp2Stream
-
timeToFirstByte
<number> 从PerformanceEntry
startTime
到接收到第一个DATA
帧之间经过的毫秒数。¥
timeToFirstByte
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and the reception of the firstDATA
frame. -
timeToFirstByteSent
<number> 从PerformanceEntry
startTime
到发送的第一个DATA
帧之间经过的毫秒数。¥
timeToFirstByteSent
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and sending of the firstDATA
frame. -
timeToFirstHeader
<number> 从PerformanceEntry
startTime
到接收到第一个标头之间经过的毫秒数。¥
timeToFirstHeader
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and the reception of the first header.
如果 name
等于 Http2Session
,则 PerformanceEntry
将包含以下附加属性:
¥If name
is equal to Http2Session
, the PerformanceEntry
will contain the
following additional properties:
-
bytesRead
<number> 为此Http2Session
接收的字节数。¥
bytesRead
<number> The number of bytes received for thisHttp2Session
. -
bytesWritten
<number> 为此Http2Session
发送的字节数。¥
bytesWritten
<number> The number of bytes sent for thisHttp2Session
. -
framesReceived
<number>Http2Session
接收到的 HTTP/2 帧数。¥
framesReceived
<number> The number of HTTP/2 frames received by theHttp2Session
. -
framesSent
<number>Http2Session
发送的 HTTP/2 帧数。¥
framesSent
<number> The number of HTTP/2 frames sent by theHttp2Session
. -
maxConcurrentStreams
<number>Http2Session
生命周期内同时打开的最大流数。¥
maxConcurrentStreams
<number> The maximum number of streams concurrently open during the lifetime of theHttp2Session
. -
pingRTT
<number> 从发送PING
帧到接收到它的确认所经过的毫秒数。只有在Http2Session
上发送了PING
帧时才会出现。¥
pingRTT
<number> The number of milliseconds elapsed since the transmission of aPING
frame and the reception of its acknowledgment. Only present if aPING
frame has been sent on theHttp2Session
. -
streamAverageDuration
<number> 所有Http2Stream
实例的平均持续时间(以毫秒为单位)¥
streamAverageDuration
<number> The average duration (in milliseconds) for allHttp2Stream
instances. -
streamCount
<number>Http2Session
处理的Http2Stream
实例的数量。¥
streamCount
<number> The number ofHttp2Stream
instances processed by theHttp2Session
. -
type
<string>'server'
或'client'
来标识Http2Session
的类型。¥
type
<string> Either'server'
or'client'
to identify the type ofHttp2Session
.
关于 :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.