NodeJS原生支持http2协议

18

NodeJS 4.x或5.x原生支持HTTP/2协议吗?我知道有http2包,但它是外部的东西。

是否有计划将http2支持合并到Node的核心中?

4个回答

9

--expose-http2 标志启用实验性的 HTTP2 支持。此标志可在 2017 年 8 月 5 日之后(Node v8.4.0)的夜间构建中使用(拉取请求)。

node --expose-http2 client.js

client.js

const http2 = require('http2');
const client = http2.connect('https://stackoverflow.com');

const req = client.request();
req.setEncoding('utf8');

req.on('response', (headers, flags) => {
  console.log(headers);
});

let data = '';
req.on('data', (d) => data += d);
req.on('end', () => client.destroy());
req.end();

自Node v8.5.0版本以来,也可以添加--experimental-modules标志。
node --expose-http2 --experimental-modules client.mjs

client.mjs

import http2 from 'http2';

const client = http2.connect('https://stackoverflow.com');

我使用NVS(Node版本切换器)来测试每晚的构建。

nvs add nightly
nvs use nightly

不要忘记添加 process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; 以便能够建立 SSL 连接并使用自签名证书。 - Alex Ivasyuv
请参考Node.js文档中最新的客户端示例:https://nodejs.org/api/http2.html#http2_client_side_example。 - Ferdinand Prantl

8

2

从node v8.8.1开始,运行代码时不再需要使用--expose-http2标志。

使用Node.js公开的兼容性API是开始使用HTTP/2最简单的方法。

const http2 = require('http2');
const fs = require('fs');

const options = {
    key: fs.readFileSync('./selfsigned.key'),
    cert: fs.readFileSync('./selfsigned.crt'),
    allowHTTP1: true
}

const server = http2.createSecureServer(options, (req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.end('ok');
});

server.listen(443);

我在这里写了更多关于如何使用Node.js公开的本机HTTP/2创建服务器的内容,请参考此处


请参阅Node.js文档中最新的服务器端示例:https://nodejs.org/api/http2.html#http2_server_side_example。 - Ferdinand Prantl

1
Node 8.4.0发布了一个实验性的Http2 API。该文档在此 nodejs http2

你知道Node.js中的http2支持何时不再是实验性的吗? - funkenstrahlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接