How to get data in the axios header to a component in Vue

I have an axios apiClient and I’m trying to get the email stored in localStorage into the header. In my component I tried using

response.headers['email']

and assigning it to an email variable but I’m getting undefined. I’m getting the email in localStorage but not able to get it in the component. Any help will be greatly appreciated.

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

Here is the method in my component where I need the email data

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

getAllOrders() does an axios get.

Answer

You set the request interceptor but you’re checking the response header, and those are two different objects. The response is from the server and won’t be affected by a request interceptor.

You can create a different interceptor for the response:

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