0
votes

I want to send POST with authorization to my REST api, but keep getting unauthorized. Everything works in postman, I have CORS enabled on the server.

      axios
    .post("/api/listings", {
      headers: {
        'Authorization': 'Bearer ' + this.token,

      }

The header seems to appear to request payload in chrome debuggin tools.

I get the token from localStorage and it is definitely there.

1
when you check your network tab for the API request, what is set for the authorization in request header? and for the localStorage, when do you update it with the token data?hamid niakan
Funny thing, in the network tab request headers i cant see the authorization header, it appears only in payload. As for the token i set it on button click of a fake login, and i get the token from the api.PoeMcMoe

1 Answers

0
votes

My issue was that the header was being sent as an object in request body and not as a header.

Fixed the issue using this code:

      axios
    .request({
      url: "api/listings",
      method: "POST",
      headers: {
        Authorization: "Bearer " + this.token,
      },
      data:{
      ListingName: this.name
      }

    })
    .then((response) => {
      console.log(response);
    });
}