node.js 服务器和带有 express.js 的 HTTP/2 (2.0)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28639995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:27:20  来源:igfitidea点击:

node.js server and HTTP/2 (2.0) with express.js

node.jshttpexpresshttp2

提问by WHITECOLOR

Is it possible currently to get node.js HTTP/2 (HTTP 2.0) server? And http 2.0 version of express.js?

当前是否可以获取 node.js HTTP/2 (HTTP 2.0) 服务器?还有 http 2.0 版本的 express.js?

采纳答案by Gajus

If you are using express@^5and http2@^3.3.4, then the correct way to start the server is:

如果您使用express@^5and 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 */
    });

Notice the https2.raw. This is required if you want to accept TCP connections.

请注意https2.raw. 如果您想接受 TCP 连接,这是必需的。

Note that at the time of this writing (2016 05 06), none of the major browsers support HTTP2 over TCP.

请注意,在撰写本文时(2016 年 05 月 6 日),没有一个主要浏览器支持 HTTP2 over TCP

If you want to accept TCP and TLS connections, then you need to start the server using the default createServermethod:

如果要接受 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 */
    });

Note that at the time of this writing, I did manage to make expressand http2to work (see https://github.com/molnarg/node-http2/issues/100#issuecomment-217417055). However, I have managed to get http2 (and SPDY) to work using spdypackage.

请注意,在撰写本文时,我确实设法制作expresshttp2开始工作(请参阅https://github.com/molnarg/node-http2/issues/100#issuecomment-217417055)。但是,我已经设法使用 package.json 使 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 */
    });

回答by HDK

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);

EDIT

编辑

This code snippet was taken from a conversation on Github.

此代码片段取自Github 上的对话。

回答by Jashepp

This issue is still around today (over a year later), so I decided to have a go at making a workaround to make express and http2 packages work nicely together. I have created a npm package that does exactly that: https://www.npmjs.com/package/express-http2-workaround

这个问题今天仍然存在(一年多之后),所以我决定尝试做一个解决方法,让 express 和 http2 包很好地协同工作。我创建了一个 npm 包,它完全可以做到这一点:https: //www.npmjs.com/package/express-http2-workaround

Install via NPM: npm install express-http2-workaround --save

通过 NPM 安装: npm install express-http2-workaround --save

// Require Modules
var fs = require('fs');
var express = require('express');
var http = require('http');
var http2 = require('http2');

// Create Express Application
var app = express();

// Make HTTP2 work with Express (this must be before any other middleware)
require('express-http2-workaround')({ express:express, http2:http2, app:app });

// Setup HTTP/1.x Server
var httpServer = http.Server(app);
httpServer.listen(80,function(){
  console.log("Express HTTP/1 server started");
});

// Setup HTTP/2 Server
var httpsOptions = {
    'key' : fs.readFileSync(__dirname + '/keys/ssl.key'),
    'cert' : fs.readFileSync(__dirname + '/keys/ssl.crt'),
    'ca' : fs.readFileSync(__dirname + '/keys/ssl.crt')
};
var http2Server = http2.createServer(httpsOptions,app);
http2Server.listen(443,function(){
  console.log("Express HTTP/2 server started");
});

// Serve some content
app.get('/', function(req,res){
    res.send('Hello World! Via HTTP '+req.httpVersion);
});

The above code is a working express application that uses both the nodejs http module (for HTTP/1.x) and the http2 module (for HTTP/2).

上面的代码是一个使用 nodejs http 模块(用于 HTTP/1.x)和 http2 模块(用于 HTTP/2)的快速应用程序。

As mentioned in the readme, this creates new express request and response objects and sets their prototypes to http2's IncomingMessage and ServerResponse objects. By default, it's the inbuilt nodejs http IncomingMessage and ServerResponse objects.

如自述文件中所述,这会创建新的快速请求和响应对象,并将其原型设置为 http2 的 IncomingMessage 和 ServerResponse 对象。默认情况下,它是内置的 nodejs http IncomingMessage 和 ServerResponse 对象。

I hope this helps :)

我希望这有帮助 :)

回答by Saurabh kumar

const http2 = require('http2');

const spdy = require('spdy');

const express = require('express');

const bodyParser = require('body-parser');
const fs = require('fs');

const app = express();

app.use(bodyParser.json());

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type Authorization');
    next();
})

const data = {
    name: 'Saurabh Kumar',
    phone:1234567898
}

app.get('/data', (req, res, next) => {
    console.log(data)
    res.status(200).json(data);
    next()
})

const options = {
    key: fs.readFileSync('localhost-privkey.pem'),
    cert: fs.readFileSync('localhost-cert.pem')
}
console.log(options)
const server = http2.createServer({ options }, app);

server.listen(5000, (err) => {
    if (err) {
        throw new Error(err);
    }

    console.log('Listening on port: ' + 5000 + '.');
})

Everything is working fine in the about code but when I try to hit the end-point with the postman, I didn't get any response.

在 about 代码中一切正常,但是当我尝试通过邮递员到达终点时,我没有得到任何回应。