How to force SSL / https in Express.js

后端 未结 8 1727
小鲜肉
小鲜肉 2020-11-27 11:54

I am trying to create a middleware for Express.js to redirect all non-secure (port 80) traffic to the secured SSL port (443). Unfortunately there is no information in an Exp

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 12:31

    Try this example :

    var express = require('express');
            var app = express();
            // set up a route to redirect http to https
            app.use(function (req, res, next) {
            if (!/https/.test(req.protocol)) {
                res.redirect("https://" + req.headers.host + req.url);
            } else {
                return next();
            }
            });
            var webServer = app.listen(port, function () {
                console.log('Listening on port %d', webServer.address().port);
            });
    

提交回复
热议问题