Reputation: 1551
I've got these two javascript code blocks interacting with remote api:
first:
const url = `${process.env.REACT_APP_USERS_SERVICE_URL}/auth/status`;
const headers = {'Content-Type': 'application/json', 'Authorization': `Bearer ${window.localStorage.authToken}`};
return axios.get(url, headers).then(res => {console.log(res.data.data)}).catch(err => {
console.log(err);
});
^ getting status code 401
second:
const options = {
url: `${process.env.REACT_APP_USERS_SERVICE_URL}/auth/status`,
method: 'get',
headers: {'Content-Type': 'application/json', 'Authorization': `Bearer ${window.localStorage.authToken}`}
};
return axios(options).then(res => {console.log(res.data.data)}).catch(err => {console.log(err)});
^ getting status code 200
My question is why both code blocks don't behave the same ? They appear to do same job.
Upvotes: 0
Views: 51
Reputation: 3229
The second parameter of axios.get
should be an axios configuration, not headers directly. The configuration of course can include headers. Try this modified example of the first attempt and see if it resolves your issue.
const url = `${process.env.REACT_APP_USERS_SERVICE_URL}/auth/status`;
const myHeaders = {'Content-Type': 'application/json', 'Authorization': `Bearer ${window.localStorage.authToken}`};
return axios.get(url, { headers: myHeaders }).then(res => {console.log(res.data.data)}).catch(err => {
console.log(err);
});
Upvotes: 0
Reputation: 1479
Looking at their docs they state axios.get(...)
is an alias for axios(...)
with some predefined behavior. As mentioned in the comments you're passing in the headers
object into what should be a request config object.
So, this should fix the issue:
const url = `${process.env.REACT_APP_USERS_SERVICE_URL}/auth/status`;
const headers = {'Content-Type': 'application/json', 'Authorization': `Bearer ${window.localStorage.authToken}`}
return axios.get(url, { headers }).then(res => {console.log(res.data.data)}).catch(err => {
console.log(err);
});
Upvotes: 2