如何使用nodejs模块http2将http2与ExpressJS集成?

问题描述 投票:0回答:2

我正在使用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 = 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, () => {
   console.log('Server running')
})

我试图将 Express 服务器作为 createSecureServer() 的第二个参数传递,但我不确定我是否正确,因为我收到此错误:

[nodemon] 2.0.2 [nodemon] 随时重启,输入

rs
[nodemon] 观看目录:. [nodemon] 观看扩展:js、mjs、json [nodemon] 开始
node index.js
_http_incoming.js:96 if (this.socket.read) ^

类型错误:无法读取未定义的“可读”属性 在 IncomingMessage._read (_http_incoming.js:96:19) 在 IncomingMessage.Readable.read (stream_read.js:491:10) 在简历(_stream_read.js:976:12) 在 processTicksAndRejections (internal/process/task_queues.js:80:21) [nodemon] 应用程序崩溃 - 开始之前等待文件更改...

应该注意的是,我的证书虽然是自签名且不可靠,但加载正确。 如果可以用 NodeJS 实现,我尽量不使用第三方模块。有什么帮助吗?

node.js express http2
2个回答
29
投票

expressjs
仍然没有正式支持 Node
http2

更多详情请访问这里

但是你可以使用

node-spdy
。使用此模块,您可以在node.js中使用自然的http模块接口创建HTTP2 / SPDY服务器,并回退到常规https(对于既不支持HTTP2也不支持SPDY的浏览器):

const spdy = require('spdy')
const express = require('express')
const path = require('path')
const fs = require('fs')

const port = 3000
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 + '.')
    }
  })

有关

spdy
的更多信息,访问此处

如果您可以选择其他框架,则可以使用'KOA''HAPI',它们支持节点

http2
这可能对你有用

另外,请阅读此发布 5.0#2237。它说:

Express 5 的目标是 API 调整和删除所有代码 从 Express 存储库,移至pillarjs 中的组件 项目(https://github.com/pillarjs),至少提供基本的 支持承诺返回处理程序和完整的 HTTP/2 功能。 Express 5 将成为“pillarjs 的视图” 是这些组件的排列。


0
投票

我找到了两种如何使用 Express.js 运行 HTTP2 服务器的解决方案。

解决方案1(来源:https://dirask.com/snippets/Express-js-run-server-using-HTTP2-h2-or-h2c-p5ddRD):

const fs = require('fs');
const path = require('path');
const spdy = require('spdy');        // npm install spdy
const express = require('express');  // npm install express

const credentials = {
    key: fs.readFileSync(path.join(__dirname, 'key.pem'), 'utf8'),
    cert: fs.readFileSync(path.join(__dirname, 'cert.pem'), 'utf8'),
};

const app = express();

// ...

app.get('/', (request, response) => {
    response.send('Hello World!');
});

// ...

const server = spdy.createServer(credentials, app);

server.listen(8443, () => console.log('Server started on https://localhost:8443'));

解决方案2(来源:https://dirask.com/snippets/Express-js-run-server-using-HTTP2-h2-or-h2c-1b88wp):

const fs = require('fs');
const path = require('path');
const http2 = require('http2');
const express = require('express');              // npm install express
const bridge = require('http2-express-bridge');  // npm install http2-express-bridge

const credentials = {
    key: fs.readFileSync(path.join(__dirname, 'key.pem'), 'utf8'),
    cert: fs.readFileSync(path.join(__dirname, 'cert.pem'), 'utf8'),
};

const app = bridge(express);

// ...

app.get('/', (request, response) => {
    response.send('Hello World!');
});

// ...

const server = http2.createSecureServer(credentials, app);

server.listen(8443, () => console.log('Server started on https://localhost:8443'));
© www.soinside.com 2019 - 2024. All rights reserved.