【问题标题】:Accessing bearer token from axios从 axios 访问不记名令牌
【发布时间】:2020-02-09 20:45:53
【问题描述】:

我可以使用什么代码来访问存储在 localStorage 中的不记名令牌?

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

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

【问题讨论】:

    标签: vue.js vuejs2 axios authorization vuex


    【解决方案1】:

    这是有效的!感谢 DigitalDrifter 向我展示了 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}`
      }
    });
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 1970-01-01
        • 2017-04-20
        • 2018-05-06
        • 2019-04-07
        • 2022-09-30
        • 1970-01-01
        • 2017-06-02
        • 1970-01-01
        相关资源
        最近更新 更多