Nodejs res.redirect不工作?

我有我的Angularjs网站,我试图将所有的Httpstream量路由到Https ,为此,我已经写了下面的代码,但它不工作,每次我打开我的网站上Httpredirect没有发生。

 var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); // Website part added var bodyParser = require('body-parser') app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })) app.use(function(req,res,next) { if(req.headers["x-forwarded-proto"] == "http") { res.redirect("https://" + req.headers.host + req.url); return next(); } else { console.log('Request was not HTTP'); return next(); } }); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.get('*', function(req, res) { res.sendFile(__dirname + '/public/index.html'); }); 

任何人都可以告诉我为什么这不工作?

编辑 – 我注意到,每当我打开我的网站,那么most of the times这个中间件not getting called 。 这怎么可能 ??

编辑 – 我有我的集base href="/"在我的index.html会导致任何问题。

这是因为在所有情况下都不能依赖x-forwarded-proto头。

当你在一个代理后面运行你的应用程序时,通常会设置x-forwarded-proto ,显然这不是你的情况。

改用req.protocol会更好一些:

 if (req.protocol === "http") { res.redirect("https://" + req.headers.host + req.url); } else { console.log('Request was not HTTP'); return next(); } 

或者你可以使用方便的快速请求属性req.secure 。