Listen on HTTP and HTTPS for a single express app

后端 未结 6 683
时光取名叫无心
时光取名叫无心 2020-12-02 09:36

Can I create an Express server listening on both HTTP and HTTPS, with the same routes and the same middlewares?

Currently I do this with Express on HTTP, with stunne

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 10:31

    To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following

    Create an express app:

    var express = require('express');
    var app = express();
    

    The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.

    You can do so as follows:

    var express = require('express');
    var https = require('https');
    var http = require('http');
    var fs = require('fs');
    var app = express();
    
    var options = {
      key: fs.readFileSync('/path/to/key.pem'),
      cert: fs.readFileSync('/path/to/cert.pem'),
      ca: fs.readFileSync('/path/to/ca.pem')
    };
    
    http.createServer(app).listen(80);
    https.createServer(options, app).listen(443);
    

    For complete detail see the doc

提交回复
热议问题