如何使用Express 4.0强制https重定向到heroku?

mik*_*aub 2 javascript heroku node.js express

我不明白为什么我的下面的代码没有完成这个?有人能解释我哪里错了吗?所有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;
Run Code Online (Sandbox Code Playgroud)

我已经做了一些搜索,看起来我应该工作.

And*_*ers 7

你的中间件的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);
Run Code Online (Sandbox Code Playgroud)

  • 很简单,谢谢!并不是说它会显着影响性能,但在我看来,将If语句置于整个代码段而不是添加生产之外的中间件更有意义. (2认同)