NodeJS 4.x或5.x原生支持HTTP/2协议吗?我知道有http2包,但它是外部的东西。
是否有计划将http2支持合并到Node的核心中?
--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();
--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
从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创建服务器的内容,请参考此处。
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
以便能够建立 SSL 连接并使用自签名证书。 - Alex Ivasyuv