In my react app i am using axios to perform the REST api requests.
But it\'s unable to send the Authorization header with the request.
Here is my co
You can create config once and use it everywhere.
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
This is what i also faced. The token which u are passing is not correct.
Just Hardcode the token and pass, you will get the correct response. But if token is not passed in single quote '', then it will surely fail. It must be in format 'Authorization': 'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ', where after Bearer one space must be present, also inside single quotes, this is very important.
var token = "YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ";
var headers = {
Authorization: "Bearer " + token,
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
};
IMP: The above code will work But if u post something like:
'Authorization': 'Bearer '+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ, it will fail
or-----the below code also will fail, i hope u understand the basic difference
var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;
var headers = {
Authorization: "Bearer " + token,
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
};
This works and I need to set the token only once in my app.js
:
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
Then I can make requests in my components without setting the header again.
"axios": "^0.19.0",