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


  • headers <HTTP/2 Headers Object>
  • options <Object>
    • endStream <boolean> 设置为 true 表示响应将不包含有效负载数据。
    • waitForTrailers <boolean> 当为 true 时,Http2Stream 将在发送完最后的 DATA 帧后触发 'wantTrailers' 事件。
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() 方法将尾随标头字段发送到对等方。

当设置了 options.waitForTrailers,则传输完最后的 DATA 帧时,Http2Stream 不会自动关闭。 用户代码必须调用 http2stream.sendTrailers()http2stream.close() 来关闭 Http2Stream

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');
});
  • headers <HTTP/2 Headers Object>
  • options <Object>
    • endStream <boolean> Set to true to indicate that the response will not include payload data.
    • waitForTrailers <boolean> When true, the Http2Stream will emit the 'wantTrailers' event after the final DATA frame has been sent.
const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 });
  stream.end('some data');
});

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.

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.

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');
});