Search code examples
javascriptnode.jsaxiosvuejs3vuex

Vue3 doesn't detect bearer token right before it gets stored


I have this code where I call my API for a login and in response I get the token.

With that, I can then call my API using the Bearer token and get the current logged in user data.

try {
  const response = await axios.post('user/login', {
  email: this.email,
  password: this.password
  })
  .then( async (response) => {
    console.log(response.data)

    localStorage.setItem('token', response.data.token);

    const userdata = await axios.get('user/userdata');

    this.$store.dispatch('user', userdata.data.userDataDTO);

    this.$router.push('/home');
  })
  .catch(err => {
  console.log(err)
  })           
} catch(err){
  console.log('login failed')
  this.failedToLogin = true;
}

The problem is that, for some reason, I keep getting 401 when the code gets to the userdata call, even though I've already added my token in the previous step. It doesn't matter how many times I execute this, it keeps throwing the Token and next, the 401 error.

I also programmed my app to detect if I already have the token stored when the page gets refreshed, so it automatically logs the user in. Since the token is already registered, I can just refresh the Login page and it will instantly get logged in. This makes no sense for me, can someone help?


Solution

  • Assuming that axios is not configured to fetch the token from local storage, you will need to pass it as a header in your GET user/userdata request.

    One of the ways to do that is to update your GET request to:

    const userdata = await axios.get('user/userdata', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    

    You can refer the axios documentation for more details about the request config object.