Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs Axios POST request gets HTTP422 error from Laravel backend

Hi I am using Vuejs in the frontend and Laravel in the backend. The role of Laravel is handling the API only. The frontend and backend are separated, i.e. I am not using Vuejs in Laravel's resource/js folder.

Now I am sending Axios POST request from Vuejs to Laravel. All the form input values are prevalidated using HTML5 required attribute. And when I console.log the request data, it shows all the fields filled.

In Vue file:

const data = {
   name: this.name,
   gender: this.gender,
   mobile_no: this.mobile_no,
   image: this.userImage
};
console.log("Request data . . . .", data);

const response = await this.axios
   .post(`${this.AppURL}/admin/user/create`, data, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
   })
   .then(() => {
        console.log("Success. . . . ")
           alert("Successfully Driver Added");
        })
   .catch(error => console.log(error));

And in Laravel, the request is passed through some validation. It's a simple validation to check if all the fields are filled. I am also using JWTAuth package for the authentication, and the token is generated by it. It's too much code to write them all the way down here. But I am sure you can understand what I mean.

What I am getting as a response is this

POST http://localhost:8000/api/admin/user/create 422 (Unprocessable Entity)

The actual result I am expected to get is either success or some errors that is according to some if conditions in validation or token check. I tried to figure out where this error might come from. What I think at the moment is this could be due to the absence of csrf_token in the POST request. As I'm sending the request outside Laravel, csrf_token is missing in the form. I am not 100% sure though about this.

So my question is:

  1. How can I include csrf_token in Axios POST request, when I send it from outside Laravel.

  2. If this 422 error is not related with csrf_token, what could be causing this? Any previos experiences like min? and any solutions for this?

Thanks in advance for your help.

like image 557
Maestro Dever Avatar asked Sep 06 '25 00:09

Maestro Dever


2 Answers

Please, modified catch block as @Jack suggested:

.catch(error => {
console.log("ERRRR:: ",error.response.data);

});

Now you can get errors and handle errors in the catch block.

like image 163
Gufran Hasan Avatar answered Sep 08 '25 11:09

Gufran Hasan


.catch(function (error) {
     console.log(error.response.data.errors);
});

please use this code I hope it work's.

like image 39
Mohammad Rana Avatar answered Sep 08 '25 12:09

Mohammad Rana