如何通过 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}`;
更新:
科尔的回答帮助我找到了问题所在。我使用的是 Django-cors-headers 中间件,它已经默认处理了授权头部。
但是我能够理解错误消息,并修复了 Axios 请求代码中的一个错误,该错误应该如下所示
return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });