我正在尝试将标头中的不记名令牌传递给固定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.status
中的0
而不是200
,而服务器日志仍然显示"res":{"statusCode":200}
。
答案 0 :(得分:1)
我发现了问题所在。
很明显,当我的Chrome版本-"\\"p
以及其他浏览器和旧版本的Chrome都与Version 80.0.3987.106 (Official Build) (64-bit)
结合使用时,会剥去authorization
标头模式。启用no-cors
并设置适当的标题可以解决此问题。
答案 1 :(得分:0)
尝试将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