I'm using a class that is wrapping an API. It's utilizing Axios. In order to make requests to the API I require a JWT token that's retrieved via another request using an api key:
async setAuthorizationHeader() {
const res = await this.Axios.post('/login', {
api_key: ''
});
this.AuthToken = res.data.token
this.Axios.defaults.headers.common['Authorization'] = `Bearer ${res.data.token}`
}
The class is instantiated once the script is loaded and setAuthorizationHeader
method is run within the constructor, so it sends out a login request at the start. My problem is that if I want to run another API call on page load, I can't as I'll receive a 401 since we haven't gotten the token yet.
Here's another method within my class that I would also be running on page load:
async getPromotions() {
const response = await this.Axios({
method: 'POST',
url: '/promotions',
data: {
...this.baseData,
}
})
return response.data
}
Is there any way to wait for the authorization step to complete before I run the getPromotions
request?