4

我正在尝试在我的标头中将不记名令牌传递给 fastify http 服务器。

我将请求中的标头设置为:

...
const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json'
}
const token = localStorage.getItem('token')
if (token) {
  headers['Authorization'] = `Bearer ${token}`
}
const newOptions = {
  ...options,
  mode: 'no-cors',
  headers
}
console.log('options:', newOptions)
return fetch(url, newOptions)

我的 console.log 打印:

options: {
  mode: "no-cors", 
  headers: {
    Accept: "application/json",
    Content-Type: "application/json",
    Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
  }
}

在 Chrome 网络选项卡中,我查看了标题,Authorization但那里不存在。我的路由处理函数如下:

async function user(server, options) {
  server.route({
    method: 'GET',
    url: '/user/:email',
    handler: async (req, res) => {
      const username = req.params.email
      console.log('user email:', username)
      console.log('headers:', req.headers)
      res.send({
        type: 'promoter'
      })
    }
  })
}

当我在服务器上打印标题时,它也没有Authorization,显示:

headers: { host: 'localhost:5000',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: 'application/json',
  'sec-fetch-dest': 'empty',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'no-cors',
  referer: 'http://localhost:3000/admin',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,ru;q=0.8' }

我错过了什么?

另一个有趣的问题是,当我从中运行请求时,Postman它会显示 200 个响应代码,并且 fastify 会打印200到日志中。但是,从传奇/请求运行:

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)

我得到response.status0而不是200在请求方法中,而服务器日志仍然显示"res":{"statusCode":200}.

4

2 回答 2

4

我弄清楚了问题所在。

显然,我的 Chrome 版本 -Version 80.0.3987.106 (Official Build) (64-bit)可能还有其他浏览器和旧版本的 Chrome,authorization当它与no-cors模式结合使用时,会剥离标题。启用CORS和设置适当的标头可以解决问题。

于 2020-02-21T15:53:20.673 回答
1

尝试将withCredentials: true和添加credentials: 'include'到您的选项中:

options: {
  mode: "no-cors",
  withCredentials: true, // <-- ADD THIS
  credentials: 'include', // <-- AND THIS
  headers: {
    Accept: "application/json",
    Content-Type: "application/json",
    Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
  }
}

参考:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

于 2020-02-21T13:25:45.430 回答