![](/img/trans.png)
[英]decompress gzip when receiving response using http2 module - NodeJS
[英]How to integrate http2 with ExpressJS using nodejs module 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 = 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')
})
我試圖將快速服務器作為 createSecureServer() 的第二個參數傳遞,但我不確定我是否正確,因為我收到此錯誤:
[nodemon] 2.0.2 [nodemon] 隨時重啟,輸入
rs
[nodemon] watching dir(s): 。 [nodemon] 觀看擴展:js,mjs,json [nodemon] 起始node index.js
_http_incoming.js:96 if (this.socket.readable) ^TypeError:無法在 IncomingMessage._read (_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
仍然不正式支持 Node http2
但是您可以使用node-spdy
。 使用此模塊,您可以在 node.js 中創建具有自然 http 模塊接口的 HTTP2 / SPDY 服務器,並回退到常規 https(對於既不支持 HTTP2 也不支持 SPDY 的瀏覽器)。
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 + '.')
}
})
有關spdy
更多信息,請訪問此處。
如果您可以選擇其他框架,則可以使用支持節點http2
“KOA”或“HAPI” 。 這可能對你有用
另外,請閱讀此版本 5.0#2237 ,它說:
Express 5 的目標是調整 API 並從 Express 存儲庫中刪除所有代碼,移至 pillarjs 項目( https://github.com/pillarjs )中的組件,至少為承諾返回處理程序提供基本支持和完整的 HTTP/2 功能。 Express 5 將成為“對 pillarjs 的看法”,並且將是這些組件的排列。
express 不知道底層協議,所以你可以這樣做:
const app = require('express')()
require('http2').createServer(options, app).listen(8080);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.