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

标签 node.js express redirect angular2-routing

我有一个在 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/

相关文章:

jquery - HTTP 补丁 XmlHttpRequest 支持

json - npm - 未安装;路径中的非法字符

javascript - 通过推荐人发送位置哈希

node.js - 如何在 mac 中升级 Node 版本?

node.js - 将图像文件从React前端上传到Node/Express/Mongoose/MongoDB后端(不起作用)

node.js - 使用 typescript 2 使用 sequelize 模型扩展 express 请求对象

javascript - node.js 表单处理更新和删除

html - 如何动态更改 NodeJs Express 应用程序中使用的 HTML 模板中样式的 "width"

ruby - 如何在不关注 RestClient 的情况下获取重定向 URL

Android - 获取 url 重定向