I've had a problem with axios and GET request with using Bearer token. Here is my code:
const response = await axios.post("/auth/login", {
...form
});
const token = response["token"];
if (token) {
localStorage.setItem("session", token);
console.log(token); //a234o2i3nr203fn20jef0293...
const tokenHeader = {
authorization: `Bearer ${token}`
}
const projects = await axios.get('/projects', { headers: { "authorization": `Bearer ${token}`}});
console.log(projects); //UNAUTHORIZED
}
After login to account I want to immediately fetch data about projects, so I use axios and try to use axios.get
with authorization header. But, for unknown for me reason, to my server part request has been delivered but without Bearer
string before my token
, my server had this on this request:
headers: {
authorization: "a234o2i3nr203fn20jef0293..." //axios remove `Bearer` string?
}
becuase of this, I cannot return any value because my server return me unauthorized cause this:
const token = authHeaders && authHeaders.split(" ")[1];
return me null instead of token.
Can someone tell me what is wrong with this axios request?
Thanks for any help!
Try writing "Authorization" and not "authorization". I've had this kind of problems before.
const projects = await axios.get('/projects', { headers: { "Authorization": `Bearer ${token}`}});