我正在学习如何使用NodeJS 10 LTS official documentation构建http2服务器。我将服务器端代码复制粘贴到server.js中,并在其上运行节点,但是当我尝试与邮递员(REST测试工具)连接时,我会收到错误消息。
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('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
我从邮递员收到的错误如下:
Unknown ALPN Protocol, expected `h2` to be available.
If this is a HTTP request: The server was not configured with the `allowHTTP1` option or a listener for the `unknownProtocol` event.
我尝试解决的问题:
要使正式文档中的示例起作用,还需要什么?我找不到用于此的在线资源,而先前关于stackoverflow的所有问题均与http2仍不是本机时的NodeJS的旧版本有关。
答案 0 :(得分:0)
尝试添加allowHTTP1:服务器选项中为true,表示服务器未配置allowHTTP1
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem')
});
收件人
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem'),
allowHTTP1: true
});
来自github http2文档:
allowHTTP1 {boolean}设置为true时,不支持HTTP / 2的传入客户端连接将降级为HTTP / 1.x。请参阅“ unknownProtocol”事件。请参阅ALPN协商。默认值:false。
在这里我已经在Stackoverflow Configure HTTP2 NodeJS Server
上找到了更好的答案答案 1 :(得分:0)
好的,经过深入的调查,我在很大程度上找到了令人满意的答案。