Reputation: 431
I'm reaching out to an endpoint with fetch to get a bearer token that will then be used in another fetch request for authentication. I've used Postman first and verified that the endpoints I'm accessing are working, however with my fetch requests below I get a 401.
I have checked in the console that the Authorization is updated after the first fetch and it's passed to the second however I continue to get a 401.
The first call reaches to ./auth and a bearer token is returned. That token is passed off to the next fetch request and but I am getting a 401.
What am I missing or doing wrong, a second pair of eyes could help.
const token = "./auth";
const listings = "./listings";
let clientHeaders = new Headers();
let raw = JSON.stringify({
email: "[email protected]",
password: "12345",
});
clientHeaders.append("Authorization", "");
clientHeaders.append("Content-Type", "application/json");
clientHeaders.append("Cookie", "");
let req = {
method: "POST",
headers: clientHeaders,
body: raw,
redirect: "follow",
};
fetch(token, req)
.then((response) => response.json())
.then((result) => {
return fetch(listings, {
method: "GET",
headers: {
Authorization: result.token,
"Content-Type": "application/json",
},
});
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(JSON.parse(data));
})
.catch((error) => {
console.log("error: ", error);
});
Upvotes: 0
Views: 983
Reputation: 27285
You likely need to include the literal word "Bearer" and a space preceding the token in the header:
{
Authorization: `Bearer ${result.token}`
}
// or
{
Authorization: "Bearer " + result.token
}
Upvotes: 2