在Heroku上使用Express / node我收到错误:在控制台中重定向了太多次或net :: ERR_TOO_MANY_REDIRECTS。
我是Express新手,我尝试添加重定向,以便将我的两个自定义域上的所有http请求重定向到https。这就是破坏网站的原因。如果有任何想法来修复它将是惊人的!
var express = require('express');
const path = require('path');
var app = express();
// process.env.PORT gets the port for Heroku or goes to 3000
const PORT = process.env.PORT || 3000;
app.enable('trust proxy');
// in production on Heroku - re-route everything to https
if (process.env.NODE_ENV==="production") {
app.use((req, res, next) => {
if (req.header['x-forwarded-proto'] !== 'https') {
res.redirect('https://' + req.hostname + req.url);
} else {
next()
}
})
}
app.use(express.static(path.join(__dirname, '/public')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
app.listen(PORT, function() {
console.log('Express server is up on port:' + PORT);
});
答案 0 :(得分:1)
改为使用req.header('x-forwarded-proto')
。
并确保console.log process.env.NODE_ENV
和req.header('x-forwarded-proto')
,req.hostname
,req.url
看到您的重定向按预期工作