簡體   English   中英

如何將axios header中的數據獲取到Vue中的一個組件

[英]How to get data in the axios header to a component in Vue

我有一個 axios apiClient ,我正在嘗試將存儲在localStorage中的 email 放入 header 中。 在我的組件中,我嘗試使用

response.headers['email']

並將其分配給 email 變量,但我沒有定義。 我在localStorage中獲取 email 但無法在組件中獲取它。 任何幫助將不勝感激。

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

這是我的組件中需要 email 數據的方法

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

getAllOrders()執行 axios get

您設置了請求攔截器,但您正在檢查響應header,這是兩個不同的對象。 響應來自服務器,不受請求攔截器的影響。

您可以為響應創建不同的攔截器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM