【问题标题】:How to get data in the axios header to a component in Vue如何将axios头中的数据获取到Vue中的组件
【发布时间】:2023-03-17 07:07:01
【问题描述】:

我有一个 axios apiClient,我正在尝试将存储在 localStorage 中的电子邮件放入标题中。在我的组件中,我尝试使用

response.headers['email']

并将其分配给电子邮件变量,但我没有定义。我在localStorage 中收到电子邮件,但无法在组件中收到它。任何帮助将不胜感激。

Axios

const apiClient = axios.create({
  baseURL: `${API}`,
  withCredentials: false,
  headers: {
     Accept: "application/json",
             "Content-Type": "application/json"
    }
});

apiClient.interceptors.request.use(function (config) {
  let token = JSON.parse(localStorage.getItem('token'));
  let email = JSON.parse(localStorage.getItem('email'));
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
    config.headers.email = `${email}`;
  }
  return config;
}, function (err) {
  return Promise.reject(err);
});

这是我需要电子邮件数据的组件中的方法

methods: {
  getOrders(){
    service.getAllOrders()
    .then(response => {
      this.email = response.headers['email'];
      console.log("email:", this.email)
    })
  }
}

getAllOrders() 执行 axios get

【问题讨论】:

    标签: javascript vue.js vuejs2 axios vue-component


    【解决方案1】:

    您设置了 request 拦截器,但您正在检查 response 标头,它们是两个不同的对象。响应来自服务器,不受请求拦截器的影响。

    您可以为响应创建不同的拦截器:

    apiClient.interceptors.response.use((response) => {
        response.headers.email = JSON.parse(localStorage.getItem('email'));
        return response;
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2020-07-14
      • 2019-11-26
      • 2021-09-22
      • 2021-07-22
      • 2019-06-21
      • 2019-07-03
      • 2020-07-20
      • 2019-08-02
      相关资源
      最近更新 更多