正在发送没有授权头的反应请求

问题描述 投票:1回答:1

我正在尝试在标题中将不记名令牌传递给固定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个响应代码,并将200打印固定在日志中。但是,从saga / request运行:

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

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

reactjs http-headers authorization bearer-token fastify
1个回答
0
投票

尝试将withCredentials: truecredentials: '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

© www.soinside.com 2019 - 2024. All rights reserved.