nodejs起一个http2
静态页面
其实就是复制官网的代码
其中证书 是我自己申请的可以用证书 dingshaohua.com
import fs from "fs";
import http2 from "node:http2";
const server = http2.createSecureServer({
key: fs.readFileSync("/etc/letsencrypt/live/dingshaohua.com/privkey.pem"),
cert: fs.readFileSync("/etc/letsencrypt/live/dingshaohua.com/fullchain.pem"),
});
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('<h1>Hello World</h1>');
});
server.listen(3002);
最终效果如下,访问:https://dingshaohua.com:3002
可以看到http2的接受请求处理 都在 server.on('stream',...)中,这正反映了 http2的数据都是流的本质
一个完整例子
import fs from "fs";
import http2 from "node:http2";
const server = http2.createSecureServer({
key: fs.readFileSync("/etc/letsencrypt/live/dingshaohua.com/privkey.pem"),
cert: fs.readFileSync("/etc/letsencrypt/live/dingshaohua.com/fullchain.pem"),
});
server.on("stream", (stream, headers) => {
const method = headers[":method"];
const path = headers[":path"];
if (method === "GET" && path === "/") {
stream.respond({
"content-type": "text/html; charset=utf-8",
":status": 200,
});
stream.end("<h1>Hello World</h1>");
} else if (method === "GET" && path === "/users") {
const params = { name: "张三" };
stream.respond({ ":status": 200, "content-type": "application/json" });
stream.end(JSON.stringify(params));
} else {
stream.respond({
"content-type": "text/html; charset=utf-8",
":status": 404,
});
stream.end("<h1>NOT FOUND</h1>");
}
});
server.listen(3002);
http/2特性
服务器推送
这个忽略吧,目前所有浏览器为了安全考虑 都禁止了 服务器流的推送,以下测试代码 经过测试chrome和firefox 判断将永远过不去。
// 监听流事件以处理 HTTP/2 流
server.on("stream", (stream, headers) => {
// 检查是否支持推送
if (!stream.pushAllowed) {
const msg = "客户端不支持服务器主动推送(流)";
console.log(msg);
}}
// 向客户端推送
setTimeout(() => {
stream.pushStream({ ":path": "/subscribe" }, (pushStream) => {
pushStream.respond({
"content-type": "application/json",
":status": 200,
});
pushStream.end(JSON.stringify({ name: "张三" }));
});
},3000);
});
支持
express暂不支持http2
nginx也不支持http2的代理