如何使用 express 4.0 在 heroku 上强制 https 重定向?
How to force https redirect on heroku with express 4.0?
我不明白为什么我的以下代码无法完成此操作?有人可以解释我哪里出错了吗?所有 http 请求都应该在 heroku 上重定向到 https,但在 localhost 上则不行。如果有人能给我指出这项工作的一个例子,我将非常感激。感觉这个应该很简单明了。
var app = express();
var https_redirect = function () {
return function(req, res, next) {
if(process.env.NODE_ENV === 'production'){
if(req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
};
app.use(https_redirect());
var server = app.listen(config.port, config.ip, function () {
});
exports = module.exports = app;
我已经进行了一些搜索,看起来我所拥有的应该有用。
您的中间件的 req, res, next
参数因被外部函数包装而丢失。
试试这个:
var https_redirect = function(req, res, next) {
if (process.env.NODE_ENV === 'production') {
if (req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
app.use(https_redirect);
开源express-force-ssl library checks X-Forwarded-Proto
and ought to work with Heroku. The code is very simple.
我不明白为什么我的以下代码无法完成此操作?有人可以解释我哪里出错了吗?所有 http 请求都应该在 heroku 上重定向到 https,但在 localhost 上则不行。如果有人能给我指出这项工作的一个例子,我将非常感激。感觉这个应该很简单明了。
var app = express();
var https_redirect = function () {
return function(req, res, next) {
if(process.env.NODE_ENV === 'production'){
if(req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
};
app.use(https_redirect());
var server = app.listen(config.port, config.ip, function () {
});
exports = module.exports = app;
我已经进行了一些搜索,看起来我所拥有的应该有用。
您的中间件的 req, res, next
参数因被外部函数包装而丢失。
试试这个:
var https_redirect = function(req, res, next) {
if (process.env.NODE_ENV === 'production') {
if (req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
app.use(https_redirect);
开源express-force-ssl library checks X-Forwarded-Proto
and ought to work with Heroku. The code is very simple.