美文网首页
Express获取正确的请求协议

Express获取正确的请求协议

作者: 薯条你哪里跑 | 来源:发表于2021-11-08 21:34 被阅读0次

背景

有一个node项目,由于某些原因,需要把所有http请求重定向到https

过程

需求很简单,开搞~
因为node是express框架的,这种操作理所应该在中间件中做, 在我们的入口文件中添加:

var protocolRedirect = function (req, res, next) {
  const { protocol, header,  originalUrl} = req;
  // 如果是线上环境,并且是http协议的话就跳走
  if (isOnline && protocol==='http') {
    res.redirect(`https://${headers.host}${originalUrl}`);
  }
  next()
};
app.use(protocolRedirect);

Nice,本地调试,没有问题~ 部署到沙箱环境。
这里说一下我们的沙箱环境有一层nginx转发,支持https以及http协议进行接口的访问。

部署完毕,check一下~ 访问服务对应的页面 http://域名.com/home ,发现控制台不停的发302重定向请求。就很奇怪,,明明代码里会让他重定向到https,之后就不会重定向了啊,查了查req.protocol确实是获取协议的属性,也确实是http

满篇302

登录到服务器打日志进行查看,发现日志里输出的protocol确实是http, 此时我用浏览器访问https://域名.com/home ,居然还是会输出http。。。

这可就不对了啊!!明明请求的是https啊!!

解决

打开google,一顿搜索,发现这种在(nginx)转发代理后的服务,需要将trust proxy设置成true才能正常的拿到想要的protocol,结合下实际情况,我们的沙箱有一层nginx,而且由于是内网,当https请求来到nginx之后,nginx会将请求转换成http在到服务器,所以直接拿req.protocol只能取出http;

https://stackoverflow.com/questions/39930070/nodejs-express-why-should-i-use-app-enabletrust-proxy

放上最终代码:

var protocolRedirect = function (req, res, next) {
  const { headers, originalUrl } = req;
  if (!isOnline || (isOnline && req.secure)) {
    next();
  } else {
    res.redirect(301, `https://${headers.host}${originalUrl}`);
  }
};
app.enable('trust proxy');
app.use(protocolRedirect);

相关文章

网友评论

      本文标题:Express获取正确的请求协议

      本文链接:https://www.haomeiwen.com/subject/whdpzltx.html