我正在尝试在我的标头中将不记名令牌传递给 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.status
了0
而不是200
在请求方法中,而服务器日志仍然显示"res":{"statusCode":200}
.