我该如何通过 axios.js 发送带有令牌的身份验证头?我尝试了一些方法,但都没有成功,例如:
const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });
给我这个错误:
XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.
我通过设置全局默认值成功让它工作了,但是我猜想对于单个请求来说这不是最好的方案:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
更新:
Cole的回答帮助我找到了问题所在。我正在使用django-cors-headers中间件,它已经默认处理授权标头。
但是我能够理解错误消息并修复了axios请求代码中的错误,应该像这样:
return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });
return axios.get(URLConstants.USER_URL, { headers: { Authorization: \
Bearer ${data.token}` } });` - foobar