从axios访问承载令牌

时间:2020-02-09 20:45:53

标签: 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: ???
  }
});

我无法使用axios服务发送身份验证标头。当我对现有的承载令牌进行硬编码时,它可以工作,但是当每个用户更改时,如何动态地为每个用户访问它呢?

2 个答案:

答案 0 :(得分:1)

在每个传出请求之前,可以使用request interceptor来设置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);
  });

答案 1 :(得分:1)

这是行得通的!感谢DigitalDrifter向我展示了localStorage中的getItem函数。

我一直以“用户”状态存储承载令牌,因此我检索了该对象,对其进行了解析,然后将其插入到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}`
  }
});