亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

HTTP 重定向循環 Node/Express

HTTP 重定向循環 Node/Express

FFIVE 2023-11-02 21:14:58
我有以下代碼用于嘗試將任何http流量重定向到等效的https// Add some redirect logic to ensure that https is always used in production, staging, development environmentapp.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 一次又一次地觸發。我在這里缺少一些簡單的東西嗎?任何幫助表示贊賞。
查看完整描述

2 回答

?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

添加app.enable('trust proxy')修復了問題并允許上面的代碼工作。同樣,我正在使用 Heroku。


查看完整回答
反對 回復 2023-11-02
?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

嘗試添加:到 中的協議名稱req.protocol === 'https:'。




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

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

  console.log('here')

  // 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()


  // request was via https, so do no special handling

  if(req.protocol === 'https:') return next(); // <---- here, add : after https

  res.redirect('https://' + req.headers.host + req.url)

})


/**

 * Bootstrap routes

 */

require('./routes')(app)


UPD:這是因為 url 解析器返回協議為https:. 請參閱 Nodejs repl 模式的示例


$ node

> url.parse('https://ya.ru')

Url {

  protocol: 'https:',

  slashes: true,

  auth: null,

  host: 'ya.ru',

  port: null,

  hostname: 'ya.ru',

  hash: null,

  search: null,

  query: null,

  pathname: '/',

  path: '/',

  href: 'https://ya.ru/'

}

https:,而不是https像評論中提到的那樣


查看完整回答
反對 回復 2023-11-02
  • 2 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號