0
votes
async create() {
  const data = {
    name: this.name
  };
  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: `Bearer ${this.token}`
  };
  axios
    .post("URL", data, headers)
    .then(res => {
      console.log('SUCCESS');
    })
    .catch(err => console.log(err.response));
}

The token from the login component. The token is loaded correctly as the POST request returns success when tried in Postman but the axios call returns

{ message: 'Unauthenticated.' },
  status: 401,
  statusText: 'Unauthorized'

Any pointers would be appreciated to identify the direction or root of this error.

1
Is it a CORS request? I suggest digging into the request details in the Network tab of your browser's developer tools.skirtle
You can have a really good example of what postman sends as a JavaScript code by clicking on "Code" on the postman's request window. Hope this will help you - Otherwise it's a bit complicated to solve the problem.Alex Spitz
May be you can try sending the same request to PostMan Echo, at least you would know whether your parameters are reaching properly, understand whether the issue is on client side or server.Manoj
are you sure that at the time of the call this.token is loaded correctly? try making a console.log or putting a breakpoint before making the callCosimo Chellini

1 Answers

1
votes

You're passing the headers to the axios incorrectly. Try this:

const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: `Bearer ${this.token}`
};

axios.post(URL, data, { headers })

That's why your Authorization header is not included in your request and the server returns 401.