"Extracting information from the axios header and passing it to a Vue component: A step-by-step

I am working with an axios apiClient and trying to retrieve the email stored in localStorage to use in the header of my component. I attempted to access the email by using

response.headers['email']

and storing it in a variable called email, but unfortunately, I am receiving undefined. While I can successfully fetch the email from localStorage, I am encountering difficulties passing it to the component. Any assistance on this matter would 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);
});

The following is the method within my component where I require access to the email data

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

getAllOrders() makes an axios get request.

Answer №1

Using the request interceptor is not going to impact the response header as they are separate entities. The response comes directly from the server and is not influenced by any request interceptors that may have been set.

To modify the response headers, you will need to create a distinct interceptor specifically for responses:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When invoking a function, jQuery may return an empty value

I am currently tweaking my jQuery script to retrieve a specific value upon page refresh in order to capture the return value. Initially, I attempted the following: var email_number = ''; // check if page refreshed or reloaded if (performance.n ...

What is the best approach to managing numerous files?

I have a couple of .js files: main.js require("./randomEvent.js").begin("hey"); require("./randomEvent.js").begin("hi"); require("./randomEvent.js").begin("hello"); randomEvent.js var repeat = true; exports.begin = (uniqueString) => { while (repe ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

Encountered a problem while trying to inherit from the BrowserWindow class in

I utilized the https://github.com/SimulatedGREG/electron-vue template to craft a vue electron blueprint. Alongside the primary process index.js, I fashioned a file named MainWindow.js which holds the subsequent code: import { BrowserWindow } from 'el ...

Tips on increasing the height of an element that is overflowing

When populating my timeline component with dynamically mapped data from an array, I encountered an issue where if I added more data causing the maximum height to be reached, the overflow-y element didn't display all content. Despite trying various sol ...

Use the zoom feature on D3 to enhance two graphs in an HTML document

I have been experimenting with d3 libraries lately and came across http://bl.ocks.org/jroetman/9b4c0599a4996edef0ab. I successfully used it to draw a graph based on data from a tsv file and enable zoom in and out functionality, which worked well for me. Ho ...

Invoking a function within the useEffect hook triggers a subsequent function upon its completion, yet despite implementing a useCallback, the component continues to re-render incessantly

In my useEffect function, I am calling another function that should only run once. However, this function calls another function upon completion which should also only run once. Initially, everything was working fine but then I started getting warnings abo ...

Making adjustments to the items in a v-for loop

My attempt to update items within a v-for directive is not working as expected. Let me provide you with the markup and component methods: <div class="card goal-item" v-for="goal in goals"> <div v-if="!goal.edit" class="card-body"> <p& ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...

The concept of dynamic schema in Mongoose allows for flexibility and

Currently, I am working on creating a product schema that involves setting pricing in different currencies. However, I am facing confusion regarding how to dynamically create currency options. The pricing may vary in one currency or multiple currencies as ...

Does installing the global npm package (@vue/cli) on Node v10.9 also automatically install Node v10.8?

This situation is quite puzzling and I have yet to find a definitive answer. It seems as though it was meant to happen this way, but it still feels odd. Here's the sequence of events: I completely removed Node from my OSX system. I then reinstalled ...

Looking for specific data in AngularJS using a filter

I'm facing a situation where I have to search based on filtered values. Below is the code snippet var app = angular.module('MainModule', []); app.controller('MainCtrl', function($scope) { $scope.searchText = '& ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

extracting values from deeply nested JSON array in JavaScript

Is there a way to extract values from a deeply nested JSON array? I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below var json = [{ name: 'Firstgroup', elements: [{ ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Can React.js components and packages be utilized in Vue.js, and vice versa?

Imagine you're working on a cutting-edge Angular project, but you want to incorporate components from your legacy Ember projects. You could easily achieve this by transferring and importing the component files into your new Angular project. I've ...

When a textbox is modified and a button is clicked in ASP.NET, triggering both client-side and server-side events

I have a popup that allows users to change an address. It contains three text boxes (Address, Province, and ZIP) and one DropDownList for the City. When the ZIP code is changed, an ajax call updates the province text box. I also want to later populate the ...