无法在快速后端接收授权标头?



我正在制作一个MERN应用程序。在useEffect中,我正在进行API调用,其中我正在设置一个授权令牌。但是我无法从后端报头中获取授权令牌。

useEffect(()=>{
fetch(`${API}/${userId}/courses`,{
method:"GET",
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}).then(response=>{
return response.json();
}).then(data=>{
console.log(data)
})
})

如果我尝试console.logreq.headers在后端,我得到的响应为:

{ host: 'localhost:3030',
connection: 'keep-alive'
origin: 'http://localhost:3000',
referer: 'http://localhost:3000/',
}

里面没有授权属性。但是,如果我尝试从POSTMAN进行相同的api调用,我将在header中获得授权令牌。有什么问题吗?

您必须在参数对象中将标题包装为关键字headers

fetch('${API}/${userId}/courses',{
method:"GET",
headers: {
'Authorization': 'Bearer ${token}',
'Content-Type': 'application/json'
}

最新更新