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

WHI*_*LOR 44 http node.js express http2

目前是否有可能获得node.js HTTP/2(HTTP 2.0)服务器?和http 2.0版的express.js?

小智 26

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);
Run Code Online (Sandbox Code Playgroud)

编辑

此代码段取自Github上的对话.

  • FYI这不适用于`express @ 4.13.3`和`http2 @ 3.2.0`,看起来快递不会支持它直到v5.https://github.com/molnarg/node-http2/issues/100 (12认同)

Gaj*_*jus 16

如果您正在使用express@^5http2@^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 */
    });
Run Code Online (Sandbox Code Playgroud)

请注意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 */
    });
Run Code Online (Sandbox Code Playgroud)

请注意,在撰写本文时,我确实设法制作expresshttp2工作(请参阅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 */
    });
Run Code Online (Sandbox Code Playgroud)

  • 我正在尝试遵循您的第一个示例,但是 `http2.raw.createServer(app).listen(...)` 抛出错误,因为 `http2.raw` 是 `undefined`。我需要使用原始 TCP,因为 TLS 加密正在被服务器的反向代理终止。关于如何解决这个问题有什么建议吗? (2认同)