[Vuejs]-Vue load page after save to store token auth

0👍

The problem, I believe, is that you’re getting the token while you’re making your request somewhere else.

Here is the sequence of events as I believe it to be happening.

  • auth.js contstructor starts request to get token
  • auth.js assigns token from storage (missing on first load) to default
  • somecomponent.vue makes an api call using missing token (session empty)
  • auth.js completes getToken and assigns new token to default headers
  • somecomponent.vue’s api call fails because the API call didn’t have the token

Now when you refresh the page…

  • auth.js contstructor starts request to get token
  • auth.js assigns token from storage
  • somecomponent.vue makes an api call using the token from the session storage
  • auth.js completes getToken and updates the token in the session
  • somecomponent.vue’s api call succeeds because the API call used the correct token before the getToken function got the new one

If this is the case, all you need to do is defer any api activity until you have the token. Of course this maybe isn’t straight forward, because you need to know whether the token is set, and chain the requests or have some way.

You could try just holding off on the redirect until your getToken succeeds (though I don’t know how you’re handling that) by getting the function to return a promise

  getToken(){
    let options = {
      method: "post",
      url: "/getapitoken",
      headers: {
        'Accept': 'application/json'
      }
    };
    return axios(options)
    .then(response => {
      let token = response.data.token
      if (token) {
        this.issetToken(token);
        return token;
      }
    })
    .catch(({ response }) => {
      console.warn(response); 
    });
  }

and then you may be able to use something like window.auth.getToken().then(()=>doMyRedirect())

The way I’ve handled these situations in the past is by using Vuex, and in the Vuex store keep state information, so any other function can check if the token is currently being pulled, so no other requests are being made simultaneously, but that still requires some logic to make the requests happen after.

Leave a comment