"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

Error encountered: Unexpected syntax error found in jQuery ajax call

I am attempting to send a simple request to Instagram using the code snippet below: $.getJSON("https://www.instagram.com/kidsfromthe90sband/media/?callback=?", function(data) { alert(JSON.stringify(data)); }); http://jsfiddle.net/FPhcr/731/ ...

Modify the HTML select tag to toggle from a selected checkbox

What should I do when a certain option is checked in the checkbox, and that label needs to be shown in the select tag? https://i.stack.imgur.com/ZxRNF.png Checkbox input <input type="checkbox" class="toggle-product pull-right" @if(!isset($restrictedPr ...

What could be the reason for meteor not injecting the text from my template helpers?

My goal is to dynamically generate a table displaying two different sets of data. Despite having verified returns from my database, the rendered page does not show the corresponding HTML elements as expected. Here is the template and HTML code: <templ ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Tips for categorizing items retrieved from .getJSON based on their category property

Looking to display a menu of coffee items with their respective parent categories on the page? Here's how you can start: Category Title Item Item Item Item Category Title Item Item This is what my data model looks like: { "menuItems": [ ...

Is there an issue with this code? HTML5 canvas

I am attempting to create a mesmerizing animation of a black hole simulation using the canvas element. My goal is to make objects exit the black hole if their distance from its center is greater than the black hole's radius, and to do so at variable s ...

What could be causing my CSS and Bootstrap.css styles not to be implemented on my webpage?

While working on my Ruby on Rails application, I am trying to customize the design to resemble (which can be downloaded from ). However, I am facing an issue where the style sheets are not being applied. I have moved the style sheets from the bootstrap/c ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

Is there a way to keep track of changes in multiple dropdowns without having to create a separate JavaScript function for each one

I'm looking for a way to dynamically add more dropdowns as my website grows without having to keep adding new functions to the JavaScript code. Is there a solution for this? Currently, I can add additional functions to the JavaScript like this: ...

A guide to updating a button in Angular:

Currently, I have implemented a directive that displays 3 tabs at the bottom. However, I am curious to know if it is possible to swap out "exterior" for "interior" based on whether I am on the exterior or interior page. For example, when on the exterior ...

Cross out an item in a list made with Material-UI and React.js

I am attempting to add a strike-through effect to a list item after a user clicks on it. To achieve this, I have developed a function that changes the style: const completed = () =>{ return document.getElementById("demo").style.textDecoration=&ap ...

Developing a JavaScript program that automatically updates the score in a Tic Tac Toe

I am currently working on developing a "Tic Tac Toe" game, but I have encountered an issue. Everything is functioning properly except for one aspect: when the game concludes and all squares are filled with either O or X, or when either X or O wins, it doe ...

Show the ajax appended html only after reaching a specific threshold

I am currently utilizing AJAX to fetch additional results from my database. Below is the basic script I am using: $('#loadmorebuilds-div').click(function() { $.ajax({ url: 'includes/loadmorebuilds.php?type=' + type + &ap ...

When working in Javascript, make sure to replace newline and carriage return characters in strings with empty spaces. Also, don't forget to replace the literal sequences and

When working with Javascript, I am looking to perform multiple string replacements as outlined below. Remove all newlines and carriage returns Swap out instances of \n with a newline character Change occurrences of \r with a carriage return char ...

What is the best way to narrow down the results of a v-for loop in VueJS using a computed property?

I've been attempting to utilize a computed property to filter the displayed results while using a v-for loop. However, despite setting the bars.js data to only show one item with 'true', all bars are still visible in my application. I expect ...

Obtain the API key from the .env file and incorporate it into the boot files in Qu

Extract the value of GOOGLE_MAP_API variable from the .env file and pass it to gmap-vue.js located in the boot/ directory It works fine when I directly use the key like this load: { key: 'AIzaSyCw9Txxxxxxxxxxxxx', ... } However, I w ...

AngularJS and KendoUI integration experiencing delays during script evaluation

At the moment, I am conducting performance measurements and analysis on our AngularJS-KendoUI application in an effort to identify any bottlenecks. Following a helpful article and an informative presentation, I am using Chrome DevTools timeline tab to anal ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...

Monitor the x and y positions for platformer game interactions using only JavaScript and jQuery

I am currently working on a 2D platformer game as part of my college project alongside my friends. We are using jQuery and pure JS for development. So far, we have been able to move the character left and right using jQuery's animate function, and ena ...