Node 和 Angular 2 App 中的 HTTP 到 HTTPS 重定向

HTTP to HTTPS redirection in Node and Angular 2 App

我有一个在 80 和 443 端口上运行的应用程序。当用户点击 http 版本的应用程序时,它应该被重定向到 HTTPS。我已尝试使用以下代码来执行此操作。

function handleRedirects(req, res, next) {
    if (!req.secure) {
        return res.redirect('https://' + req.get('host') + req.url);
    }
    next();
}

app.use(handleRedirects);

https.createServer(credentials, app).listen(443, function() {
    console.log('App is running on port 443');
});

// all other routes are handled by Angular
app.get('/*', function(req, res) {
    console.log("Default handler\n\n\n\n")
    res.sendFile(path.join(__dirname, '/../../dist/index.html'));
});

app.listen(80, function() {
    logger.info('App is running on port 80');
    admins.refresh();
});

所以当应用程序启动时,如果我点击 localhost,它应该被重定向到 https://localhost。但它没有按预期工作。 代码有什么问题。我已提交

我只是设置 https 以便它只在生产环境中重定向,我在我的网站上使用的代码如下。

module.exports.httpsRedirect = function(req,res,next){
 if(req.headers['x-forwarded-proto'] != 'https' && process.env.NODE_ENV === 'production')
    res.redirect('https://'+req.hostname+req.url)
 else
    next() /* Continue to other routes if we're not redirecting */
};

下面的代码解决了我的问题。

var app = express();
app.get('/refresh', function (req, res) {
    res.send(200);
});
https.createServer(credentials, app).listen(443, function () {
  console.log('App is running on port 443');
});


var http = express();

http.get('/', function (req, res) {
  res.redirect('https://' + req.get('host') + req.url);
})
http.listen(80, function () {
  logger.info('App is running on port 80');
});