📅  最后修改于: 2023-12-03 14:44:39.384000             🧑  作者: Mango
在 Node.js 中,Http2ServerRequest 是用于处理 HTTP/2 请求的对象。Http2ServerRequest.stream 方法返回一个可读的流,用于从客户端接收请求的正文数据。
const stream = http2ServerRequest.stream;
返回一个可读的流(Readable Stream)对象。
const http2 = require('http2');
const fs = require('fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem')
});
server.on('stream', (stream, headers) => {
// 读取请求的正文数据
stream.on('data', (chunk) => {
console.log(`Received data: ${chunk}`);
});
// 监听流结束事件
stream.on('end', () => {
console.log('Request stream ended');
});
// 回复客户端
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello, World!</h1>');
});
server.listen(3000);
以上示例创建一个使用 HTTP/2 的安全服务器,当收到客户端的请求时,会通过 stream
事件处理函数来处理请求。在处理函数中,通过 http2ServerRequest.stream
方法获取到客户端请求的流对象,并对该流对象进行操作,如读取数据、设置回复等。
stream.on('data', ...)
可以监听流上的 data 事件,并读取请求的正文数据。stream.respond()
方法可以设置向客户端回复的响应头和状态码。stream.end()
方法可以向客户端发送回复的正文数据并结束流。请参考 Node.js 文档 获取更多详细信息。
注意: http2
模块是 Node.js v8.4.0 以上版本才支持的,且需要在支持 HTTP/2 的环境中运行。