简体   繁体   English

从 axios 访问不记名令牌

[英]Accessing bearer token from axios

What code can I use to access a bearer token that's been stored in localStorage?我可以使用什么代码来访问存储在 localStorage 中的不记名令牌?

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

I'm having trouble sending auth headers using a axios Service.我在使用 axios 服务发送身份验证标头时遇到问题。 When I hardcode the existing bearer token it works, but how can I dynamically access that for each user as it changes?当我对现有的不记名令牌进行硬编码时,它可以工作,但是如何在更改时为每个用户动态访问它?

This is what worked!这就是有效的! Thanks to DigitalDrifter for showing me the getItem function in localStorage.感谢 DigitalDrifter 向我展示了 localStorage 中的 getItem 函数。

I've been storing the bearer token in 'user' state, so I retrieved the object, parsed it, then inserted it into the Authorization header.我一直将不记名令牌存储在“用户”状态,因此我检索了该对象,对其进行了解析,然后将其插入到 Authorization 标头中。

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

A request interceptor can be used to set the Authorization header prior to each outgoing request.请求拦截器可用于在每个传出请求之前设置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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM