HTTP 重定向循环 Node/Express

我有以下代码用于尝试将任何http流量重定向到等效的https


// Add some redirect logic to ensure that https is always used in production, staging, development environment

app.use((req, res, next) => {

  // if NODE_ENV is 'local' don't redirect to https, only do so for our deployed server environments

  if(!['development', 'staging', 'production'].includes(process.env.NODE_ENV)) return next()


  if(!req.secure) {

    return res.redirect(301, `https://${req.headers.host}${req.originalUrl}`)

  }


  next()

})


/**

 * Bootstrap routes

 */

require('./routes')(app)

然而,当我在浏览器中测试这个并输入类似http://example.com我在浏览器中收到重定向循环警告和我的 papertrail 日志中的内容时,我可以看到 console.log 一次又一次地触发。


我在这里缺少一些简单的东西吗?任何帮助表示赞赏。


FFIVE
浏览 118回答 2
2回答

慕运维8079593

添加app.enable('trust proxy')修复了问题并允许上面的代码工作。同样,我正在使用 Heroku。

墨色风雨

尝试添加:到 中的协议名称req.protocol === 'https:'。// Add some redirect logic to ensure that https is always used in production, staging, development environmentapp.use((req, res, next) => {&nbsp; console.log('here')&nbsp; // if NODE_ENV is 'local' don't redirect to https, only do so for our deployed server environments&nbsp; if(!['development', 'staging', 'production'].includes(process.env.NODE_ENV)) return next()&nbsp; // request was via https, so do no special handling&nbsp; if(req.protocol === 'https:') return next(); // <---- here, add : after https&nbsp; res.redirect('https://' + req.headers.host + req.url)})/**&nbsp;* Bootstrap routes&nbsp;*/require('./routes')(app)UPD:这是因为 url 解析器返回协议为https:. 请参阅 Nodejs repl 模式的示例$ node> url.parse('https://ya.ru')Url {&nbsp; protocol: 'https:',&nbsp; slashes: true,&nbsp; auth: null,&nbsp; host: 'ya.ru',&nbsp; port: null,&nbsp; hostname: 'ya.ru',&nbsp; hash: null,&nbsp; search: null,&nbsp; query: null,&nbsp; pathname: '/',&nbsp; path: '/',&nbsp; href: 'https://ya.ru/'}https:,而不是https像评论中提到的那样
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript