【发布时间】:2017-04-14 01:57:43
【问题描述】:
所以堆栈是这样的:Express & Angular 部署到 Heroku。我正在尝试通过使用下面突出显示的代码的简单重定向来为强制通过 HTTPS 的应用程序提供服务。但是,当我在浏览器中打开 URL 时,出现“重定向过多”错误。
当我输入 http://[myurl].com 时,我可以看到浏览器中的 URL 更改为 https://[myurl].com,但该地址没有显示任何内容。它只是显示“重定向过多”。这证明它成功重定向了,但我觉得 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}!`);
});
这是您访问 http://[myurl].com 时的 heroku 日志示例(我屏蔽了 URL):
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 最新版)在“网络”标签中一遍又一遍地显示这些请求:
'请求网址: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}!`);
});
【问题讨论】: