The data retrieved from localStorage following a redirection using $router.push is empty

When I log in using my Login component, a request is made to retrieve a JWT token which is then saved into localStorage before navigating to the Home page.

const response = await axios.post('/auth/login', {
    login: this.login,
    password: this.password
});

localStorage.setItem('token', response.data);
this.$router.push('/');

In axios.js, I configure the header with the retrieved token:

axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;

Upon landing on the Home page after redirection, the "mounted" hook attempts to make a request using the stored token but encounters an error 401 due to the Authorization header being set as "Bearer null". However, upon refreshing the page, everything works fine. Why does it show up as null after redirection?

async mounted() {
    const response = await axios.get('cinema/items');
    this.cinemas = response.data;
  }

Answer №1

Interceptors in Axios are special functions that are executed for each request and response.

For your scenario:

axios.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
    return config;
  },
  error => {
      return Promise.reject(error);
  }
)

One notable difference between setting headers during axios initialization versus on every request is the timing - with initialization, it occurs before you have obtained the token.

You may notice that the functionality works after refreshing the page because axios is re-initialized, allowing access to the token stored in localStorage.
Avoid retrieving and setting a new token every app startup. It's advisable to only fetch a new token when none exists in localStorage or if the current one has expired.

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

Save all user information annually from the date they first sign up

Greetings! I am facing an issue where every time a year is added, it gets inserted between the day and month in the date of entry for a user at our company. var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow(); var dateStart = mome ...

Optimizing search engine visibility for interactive websites

I have developed a website with dynamically created pages using JavaScript and PHP. For example, check out . The content of these pages changes based on the "id" parameter. A few years ago, it was difficult for search engine crawlers to scan such dynamic ...

Struggling three.js newcomer faced with initial hurdle: "Function is undefined"

I am encountering a similar issue to the one discussed in this question: Three.js - Uncaught TypeError: undefined is not a function -- and unfortunately, the solutions provided there did not work for me. My journey with three.js began on the Getting Start ...

Issue with re-render not occurring after sorting a useState object in a table

const [team, setTeam] = useState([]); useEffect(() => { fetchTeamMembers(); }, []); const sortTeamByName = () => { const sortedTeam = team.sort((a, b) => { if (a.name < b.name) { return -1; } if (a.name ...

Enhancing Bootstrap 5 with JavaScript

I am relatively new to creating webpages and have recently started working on one using Bootstrap 5. I am looking to dynamically add or remove the "bg-opacity" Bootstrap class from my navbar based on the viewport width. I initially attempted to achieve thi ...

Best method for extracting object values from an array in Javascript using loops?

Recently Updated: Complete values of respons: "{"versions":[ { "name":"Windows 8.1 with Update 3 (build 9600)", "version_id":"11" }, { "name":"Windows 7 SP1 (build 7601)", "version_id":"9" }, { "name": ...

Is there a way to execute a script during every npm install process?

Is it possible to set up pre-push hooks for Git with each npm install action? Are there any alternative solutions that do not involve installing tools like Gulp, and instead rely solely on npm? ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

Is it possible to halt the set timeout function in an AJAX call once a specific condition has been satisfied?

I have the following code snippet that is currently functioning correctly, but I am looking to implement a way to disable the automatic refreshing once a specific condition is satisfied. enter code here $(document).ready(function() { ...

Expanding content based on height using React

I have successfully implemented the show more/show less feature. However, my issue is that I would like it to be based on the number of lines or screen height rather than the number of characters. This is because the current setup may look awkward on certa ...

Creating a TypeScript interface for the Ethereum Window object with a request method implementation

Currently, I have a function running that imports ethers from the "ethers" library. import { ethers } from "ethers"; async function requestAccount() { await window.ethereum.request({ method: "eth_requestAccounts" }); } The problem ...

Is it possible that attaching the click event directly to the ID is effective while attaching it to the childnode is not working

Can anyone help me with a problem I'm having? When I try to target a specific element by accessing its child nodes, the click event doesn't work. However, if I use getElementById and then attach the click event through that method, it works. Idea ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...

What is the method for entering text into a span element and submitting it by hitting the "ENTER" key using Selenium in Python 3.7?

Environment: Using Python 3.7 and Selenium 3.141 Issue : I need to automate commenting on posts using Selenium in a web page. The challenge is that the comment form does not have a traditional "Submit" button; instead, it's a SPAN element where yo ...

Oops! An error occurred while using the Google Maps API. Let's fix this hic

I recently encountered an issue on my website where the Google Map displayed suddenly showed an error message saying: "Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details." Afte ...

"Implement real-time updates for input values using the onkeypress event in ReactJS

Recently, I've been exploring how to update an input based on keypress in a window using ReactJS. Specifically, I am working on developing a basic calculator with just one input field. My goal is to have the input automatically targeted whenever a key ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Can someone assist me in figuring out why the ShowDetail.html page is not opening after I submit my form?

I'm having trouble getting the shoDetail.html page to open when I submit the code. I even tried entering the complete URL, but it still won't work. Here is the code I am using: <div class="form-group row"> <div class="col-lg-12 col-md-1 ...

Dynamic collapsible navigation panels powered by Bootstrap

I am currently working on creating Bootstrap accordions to display supplementary information. However, I have encountered an issue where clicking on one accordion opens all of them simultaneously. Is there a way in HTML, CSS, or JS to prevent this from hap ...

Utilize Angular to create a dropdown filter activated by a click event

Having trouble filtering or searching for relevant data using a dropdown input? The task is to select an option from the dropdown and click on the button to filter or display the corresponding data in a table using Angular. Directly achieving this works, b ...