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

后端 未结 3 698
误落风尘
误落风尘 2020-12-23 13:49

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

3条回答
  •  春和景丽
    2020-12-23 14:02

    This issue is still around today (2016 as of writing this), so I decided to have a go at making a workaround to make express and http2 packages work nicely together: https://www.npmjs.com/package/express-http2-workaround

    Edit: Does not work on any NodeJS version above v8.4 due to the native 'http2' module.

    Install via 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).

    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.

    I hope this helps :)

提交回复
热议问题