从 axios 访问持有者令牌



我可以使用什么代码来访问存储在 localStorage 中的持有者令牌?

const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'.
Authorization: ???
}
});

我在使用 axios 服务发送身份验证标头时遇到问题。当我对现有的持有者令牌进行硬编码时,它可以工作,但是当它发生变化时,我如何为每个用户动态访问它?

这就是有效的!感謝 DigitalDrifter 向我展示 localStorage 中的 getItem 功能。

我一直将持有者令牌存储在"user"状态,因此我检索了对象,对其进行了解析,然后将其插入到授权标头中。

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}`
}
});

请求拦截器可用于在每个传出请求之前设置Authorization标头。

// 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);
});

相关内容

最新更新