简体   繁体   中英

Data taked from localStorage after rediraction with $router.push is null

In my Login component I make a request to get a JWT token, set it into localStorage and go to 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 set header with this token:

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

In Home page (where i was redirected) in mounted hook I try to make request with this token, but i get error 401, because header Authorization = Bearer null. But if I refrash the page all is work. So why is it null after redirection?

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

Axios interceptors are functions run for every request/response.

In your case:

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

The difference between setting the headers at axios init rather than on every request is that the init happens before you get the token.

The reason why it works when you refresh the page is because you re-init axios, and this time the token is found in localStorage .
Note you shouldn't get and write a new token every time you start the app. You might want to only get a new one when there isn't one in localStorage or the existing one has expired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM