http2stream.respond([headers[, options]])


  • headers HTTP/2 请求头对象|HTTP/2 原始请求头
  • options <Object>
    • endStream <boolean> 设置为 true 表示响应将不包含有效负载数据。
    • waitForTrailers <boolean> 当设置为 true 时,Http2Stream 会在最后一个 DATA 帧发送后触发 'wantTrailers' 事件。
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 });
  stream.end('some data');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 });
  stream.end('some data');
});

启动响应。当设置了 options.waitForTrailers 选项时,在将最后一块要发送的负载数据排入队列后,会立即触发 'wantTrailers' 事件。然后可以使用 http2stream.sendTrailers() 方法将尾部头字段发送给对端。

【Initiates a response. When the options.waitForTrailers option is set, the 'wantTrailers' event will be emitted immediately after queuing the last chunk of payload data to be sent. The http2stream.sendTrailers() method can then be used to sent trailing header fields to the peer.】

当设置 options.waitForTrailers 时,Http2Stream 在发送最后一个 DATA 帧后不会自动关闭。用户代码必须调用 http2stream.sendTrailers()http2stream.close() 来关闭 Http2Stream

【When options.waitForTrailers is set, the Http2Stream will not automatically close when the final DATA frame is transmitted. User code must call either http2stream.sendTrailers() or http2stream.close() to close the Http2Stream.】

import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 }, { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });
  stream.end('some data');
});const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 }, { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });
  stream.end('some data');
});