React Axios PUT/PATCH method Unauthorized, Laravel 5.7

Asked

Viewed 628 times

1

The PUT/PATCH methods available in the API via the function Route::apiResource('user','UserController'); are those: inserir a descrição da imagem aqui

GET and POST requests work normally, but in the PUT/PATCH route implementation I get the "Unauthorized" message from the API:

inserir a descrição da imagem aqui

However, when using a REST client as a Postman:

inserir a descrição da imagem aqui

I can get access to the route, so I believe my Axios request is wrong:

let header = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `${this.state.tokenType} ${this.state.token}`
  }
}
var body = new FormData();
body.append('canAddAdm', this.state.canAddAdm);
body.append('canAddUser', this.state.canAddUser);
body.append('canAddStructures', this.state.canAddStructures);
Axios.put(`${this.state.url}/api/user/{${this.state.selectedOption}}`, header, body)
  .then(res => res.data)
    .then(result => {
      console.log('result :', result);
    })
  .catch(error => {
    console.log('Error when update user: ', error.response);
  })
}

So my question is, what would I be doing wrong to be able to access Laravel’s update method via Axios?

  • It’s probably Cors’s mistake... Before the request itself the browser sends an OPTIONS request, you need to accept this type of request on the route street in the backend.

1 answer

2


I believe it is because of the order that you are passing the arguments to the Axios. If you look at the API, you will see that the put call is as follows: axios.put(url[, data[, config]])

I mean, your call should be:

Axios.put(`${this.state.url}/api/user/{${this.state.selectedOption}}`, body, header)
   .then(...)
   .catch(...)
  • Ai, catch for a mistake like this... The way is to go out and have a coffee to breathe a little... Thank you very much, I was hunting trouble thinking there was something wrong with the header and body content and not with the order as they were passed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.