I am using the Axios library for my ajax requests so I created an instance of axios.
When I hit the endpoint /user/login
, the success response will return me a token that I will use in the header for future calls as the API is secured.
The problem is when I do a console.log(authUser) the object is empty even though in the .then()
, I am setting authUser.bearerToken
.
Why is this happening? And what's the solution? Thanks. See code below.
var ax = axios.create({
baseURL: 'http://api.site.test',
timeout: 5000,
headers: {
'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx'
}
});
var authUser = {};
// log the user in
ax.post('/user/login', {
email: 'e@maiiiiiiiiil.com',
password: 'ThisIsACoolPassword123!'
})
.then(function (response) {
// set the bearer token
authUser.bearerToken = response.data.token;
ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
})
.catch(function (error) {
console.log(error);
});
console.log(authUser);