所以堆棧如下:Express & Angular部署到Heroku。我正試圖通過使用下面突出顯示的代碼進行簡單重定向來強制通過HTTPS爲應用提供服務。但是,當我在瀏覽器中打開URL時,出現「重定向太多」的錯誤。Express.js強制HTTPS/SSL重定向錯誤:重定向太多
當我輸入http://[myurl].com時,我可以在瀏覽器中看到更改爲https://[myurl].com的URL,但沒有在該地址顯示。它只是顯示'太多重定向'。這證明它成功地重定向了,但我覺得Angular會搞砸它。
當我刪除下面的重定向代碼並在瀏覽器中手動訪問HTTPS或HTTP地址時,它工作正常。
//HTTPS redirect middleware
function ensureSecure(req, res, next) {
console.log(req.protocol + process.env.PORT + '' + req.hostname + req.url);
if(req.secure || req.hostname=='localhost'){
//Secure request, continue to next middleware
next();
}else{
res.redirect('https://' + req.hostname + req.url);
console.log(req.protocol + process.env.PORT + '' + req.hostname + req.url);
}
}
//Parse the body of the request as a JSON object, part of the middleware stack (https://www.npmjs.com/package/body-parser#bodyparserjsonoptions)
app.use(bodyParser.json());
//Serve static Angular JS assets from distribution, part of the middleware stack, but only through HTTPS
app.all('*', ensureSecure);
app.use('/', express.static('dist'));
//Import routes
app.use('/api', [router_getToken, router_invokeBhApi]);
//Setup port for access
app.listen(process.env.PORT || 3000, function() {
console.log(`The server is running on port ${process.env.PORT || 3000}!`);
});
這是Heroku的日誌的樣本,當您訪問http://[myurl].com(我屏蔽的網址):
2016-11-29T21:50:34.363391+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.363468+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.402022+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.402091+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.436006+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.437454+00:00 app[web.1]: 0|app | http37436[something].com/
2016-11-29T21:50:34.479580+00:00 app[web.1]: 0|app | http37436[something].com/
的瀏覽器(Chrome最新)顯示在網絡選項卡上&這些請求在&一遍又一遍:
'請求URL:https://[myurl].com/
請求方法:GET
狀態代碼:302找到'
注意Heroku(express.js代碼中的console.log)如何顯示我正在發出HTTP請求,但我的瀏覽器正在說我正在發出HTTPS請求。如此迷茫!
編輯: 我想這也
//HTTPS redirect middleware
function ensureSecure(req, res, next) {
console.log(req.protocol + process.env.PORT + '' + req.hostname + req.url);
if (req.secure || req.hostname == 'localhost') {
//Serve Angular App
express.static('dist');
} else {
//res.redirect('https://' + req.hostname + ':' + process.env.PORT + req.url);
res.redirect('https://[myurl].com/');
}
}
//Parse the body of the request as a JSON object, part of the middleware stack (https://www.npmjs.com/package/body-parser#bodyparserjsonoptions)
app.use(bodyParser.json());
//Serve static Angular JS assets from distribution, part of the middleware stack, but only through HTTPS
app.use('/', ensureSecure);
//Import routes
app.use('/api', [router_getToken, router_invokeBhApi]);
//Setup port for access
app.listen(process.env.PORT || 3000, function() {
console.log(`The server is running on port ${process.env.PORT || 3000}!`);
});
爲我工作呢!謝謝! –