Node.js 如何使用nodejs模块http2将http2与ExpressJS集成?
我正在用nodejs和express创建一个api,我想将http2与ExpressJS集成 这是我的代码:Node.js 如何使用nodejs模块http2将http2与ExpressJS集成?,node.js,express,http2,Node.js,Express,Http2,我正在用nodejs和express创建一个api,我想将http2与ExpressJS集成 这是我的代码: 'use strict'; const http2 = require('http2'); const fs = require('fs'); const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const app =
'use strict';
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 443;
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Routes variables
const indexRouter = require('./routes/index');
// Routes uses
app.use('/', indexRouter);
// Server configurations
const key = path.join(__dirname + '/security/key.pem');
const cert = path.join(__dirname + '/security/certificate.pem');
const options = {
key: fs.readFileSync(key),
cert: fs.readFileSync(cert)
}
const server = http2.createSecureServer(options, app);
server.on('error', err => console.log(err));
server.listen(port, err => {
if (err) throw err;
})
我试图将express server作为createSecureServer()的第二个参数传递,但我不确定是否正确,因为我遇到了以下错误:
[nodemon]2.0.2[nodemon]要随时重新启动,请输入rs
[nodemon]
观看导演(s):。[nodemon]观看扩展:js、mjs、json
[nodemon]正在启动node index.js
_http_incoming.js:96 if(this.socket.readable)
^
TypeError:无法读取未定义的属性“readable”
在输入消息时读取(http_incoming.js:96:19)
在IncomingMessage.Readable.read(_stream_Readable.js:491:10)
在resume上(_stream_readable.js:976:12)
在processTicksAndRejections(internal/process/task_queues.js:80:21)[nodemon]应用程序崩溃-
正在等待文件更改,然后再开始
应该注意的是,我的证书虽然是自签名的,而且不可靠,但加载正确。
如果我可以使用NodeJS,我会尽量不使用第三方模块。有什么帮助吗?
expressjs
仍然没有正式支持Nodehttp2
但是您可以使用节点spdy
。使用此模块,您可以使用自然的http模块接口在node.js中创建HTTP2/SPDY服务器,并回退到常规https(对于既不支持HTTP2也不支持SPDY的浏览器)
有关spdy的更多数据,请参见
如果您有其他框架的选项,您可以使用支持nodehttp2
的'KOA'或'HAPI'
还有,读一下,上面写着:
express5的目标是对API进行调整&删除所有代码
从Express存储库移动到pillarjs中的组件
项目(),至少提供基本的
支持承诺返回处理程序和完整的HTTP/2
功能。Express 5将成为“pillarjs视图”,并且
是这些组件的一种安排
const port = 3000
const spdy = require('spdy')
const express = require('express')
const path = require('path')
const fs = require('fs')
const app = express()
app.get('*', (req, res) => {
res
.status(200)
.json({message: 'ok'})
})
const options = {
key: fs.readFileSync(__dirname + '/server.key'),
cert: fs.readFileSync(__dirname + '/server.crt')
}
console.log(options)
spdy
.createServer(options, app)
.listen(port, (error) => {
if (error) {
console.error(error)
return process.exit(1)
} else {
console.log('Listening on port: ' + port + '.')
}
})