Listen on HTTP and HTTPS for a single express app

后端 未结 6 671
时光取名叫无心
时光取名叫无心 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:30

    If you want to use the traditional two ports, one of the above solutions probably works, but using httpolyglot, you can really easily have http and https on the same port with the same middlewares.

    https://github.com/mscdex/httpolyglot

    Here's some skeleton code that worked for me:

    var express = require('express');
    var fs = require('fs');
    var httpolyglot = require('httpolyglot');
    var app = express();
    
    const options = {
        key: fs.readFileSync("/etc/ssl/certs/key"),
        cert: fs.readFileSync("/etc/ssl/certs/cer.cer")
    };
    
    httpolyglot.createServer(options, app).listen(port);
    

    and if you want http -> https forwarding, you can just add this middleware function before the createServer() call:

    app.use(function(req, res, next) {
        if (!req.secure ) {
                res.redirect (301, 'https://' + req.hostname + ':port' + req.originalUrl);
        }
        next();
    });
    

    This can be set up on a custom port

提交回复
热议问题