Vue.js 从axios访问承载令牌
我可以使用什么代码访问存储在localStorage中的承载令牌Vue.js 从axios访问承载令牌,vue.js,vuejs2,axios,authorization,vuex,Vue.js,Vuejs2,Axios,Authorization,Vuex,我可以使用什么代码访问存储在localStorage中的承载令牌 const apiClient = axios.create({ baseURL: 'http://localhost:5000/api/v1', withCredentials: false, headers: { Accept: 'application/json', 'Content-Type': 'application/json'. Authorization: ??? } });
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'.
Authorization: ???
}
});
使用axios服务发送身份验证标头时遇到问题。当我对现有的承载令牌进行硬编码时,它可以工作,但如何在每个用户更改时动态访问该令牌?A可用于在每个传出请求之前设置授权
头
// Add a request interceptor
axios.interceptors.request.use(function (config) {
let token = localStorage.getItem('bearer_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
这就是成功的原因!感谢DigitalDriver向我展示了localStorage中的getItem函数 我一直在“用户”状态下存储承载令牌,所以我检索了对象,对其进行了解析,然后将其插入到授权头中
const user = JSON.parse(localStorage.getItem('user'));
const token = user.token;
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
});