作者:小樣兒靠邊詀_853 | 来源:互联网 | 2023-05-21 08:30
目前是否有可能获得node.js HTTP/2(HTTP 2.0)服务器?和http 2.0版的express.js?
1> 小智..:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello, http2!');
});
var optiOns= {
key: fs.readFileSync('./example/localhost.key'),
cert: fs.readFileSync('./example/localhost.crt')
};
require('http2').createServer(options, app).listen(8080);
编辑
此代码段取自Github上的对话.
FYI这不适用于`express @ 4.13.3`和`http2 @ 3.2.0`,看起来快递不会支持它直到v5.https://github.com/molnarg/node-http2/issues/100
2> Gajus..:
如果您正在使用express@^5
和http2@^3.3.4
,那么启动服务器的正确方法是:
const http2 = require('http2');
const express = require('express');
const app = express();
// app.use('/', ..);
http2
.raw
.createServer(app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});
请注意https2.raw
.如果要接受TCP连接,则必须执行此操作.
请注意,在撰写本文时(2016 05 06),主流浏览器都没有支持HTTP上的HTTP2.
如果要接受TCP和TLS连接,则需要使用默认createServer
方法启动服务器:
const http2 = require('http2');
const express = require('express');
const fs = require('fs');
const app = express();
// app.use('/', ..);
http2
.createServer({
key: fs.readFileSync('./localhost.key'),
cert: fs.readFileSync('./localhost.crt')
}, app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});
请注意,在撰写本文时,我确实设法制作express
和http2
工作(请参阅https://github.com/molnarg/node-http2/issues/100#issuecomment-217417055).但是,我设法让http2(和SPDY)使用spdy
包工作.
const spdy = require('spdy');
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.json({foo: 'test'});
});
spdy
.createServer({
key: fs.readFileSync(path.resolve(__dirname, './localhost.key')),
cert: fs.readFileSync(path.resolve(__dirname, './localhost.crt'))
}, app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});