gpt4 book ai didi

node.js - Node 和 Angular 2 App 中的 HTTP 到 HTTPS 重定向

转载 作者:搜寻专家 更新时间:2023-10-31 23:51:41 26 4
gpt4 key购买 nike

我有一个在 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 redirection for all routes node.js/express - Security concerns

最佳答案

我只是设置 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 */
};

关于node.js - Node 和 Angular 2 App 中的 HTTP 到 HTTPS 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com