来自官方文档和邮递员的简单http2 NodeJS Server无法正常工作

时间:2019-04-24 11:01:57

标签: node.js http2

我正在学习如何使用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.

我尝试解决的问题:

  1. 根据官方文档的要求,我创建了私有和公共证书(.pem)。
  2. 我已将公共证书包含在邮递员软件中。因此,现在我收到的唯一错误是上述错误(未知的ALPN协议)。

要使正式文档中的示例起作用,还需要什么?我找不到用于此的在线资源,而先前关于stackoverflow的所有问题均与http2仍不是本机时的NodeJS的旧版本有关。

2 个答案:

答案 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)

好的,经过深入的调查,我在很大程度上找到了令人满意的答案。

  1. https请求应为https://localhost:8443/stream,以使用Hello World从服务器获得响应。没有流路径,就没有响应。
  2. 邮递员在安装公共证书后给出403响应,但是失眠没有给出任何响应。
  3. 使用“网络”标签中的google chrome开发人员工具,我终于可以从服务器获得响应200 OK,如下所示。

enter image description here