0

I'm working with Laravel and VueJS and for all of my post and put methods server returns the newly created data after submitting the form, in the case of errors, I cannot access them from the browser console. This is what I can see in the newtwork tab.The purpose is to customize form errors according to errors that is being returned by the server

Here is my backend code :

private function validateForm($data){
    return Validator::make($data,
    [
        'fname' => ['required', 'string','min:2' ,'max:255'],
        'lname' => ['required', 'string','min:2' ,'max:255'],
        // 'mname' => ['string','min:2' ,'max:255'],
        'company' => ['string','min:2' ,'max:255'],
        'title' => ['string','min:2' ,'max:255'],
        'phone_number' => ['string','min:13' ,'max:13'],
        'city' => ['required', 'string','min:2' ,'max:100'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed']
        // 'password_confirm'=>['required','string']
    ]
  )->validate();
}
//Register
public function register(Request $request){
    $data=$this->validateForm($request->all());
    $data['password']=Hash::make($data['password']);
    $user=new User($data);
    $user->save();
    return response()->json($user);

}  

And my code from the front-end:

export default{
    data(){
        return {
            form:{
                email:'',
                password:'',
                password_confirmation:'',
                fname:'',
                lname:'',
                city:''
            },
            formError:''
        }
    },
    methods:{
        //This should be a POST method through axios
        register:async function(){
           try{
               const res=await axios.post('api/register',
               {
                   email:this.form.email,
                   password:this.form.password,
                   password_confirmation:this.form.password_confirmation,
                   fname:this.form.fname,
                   lname:this.form.lname,
                   city:this.form.city
               });
               //Une fois inscrit,il est redirige vers la page de login
               this.$router.push({path:'/login'});
               console.log("My data : ",res.data);
           }catch(err){
                   console.log("Errors",err);
           }

        }
    }
    }

When there are no errors, everything goes fine, but when there are errors, this is what I get in the browser console tab:

Devtools console tab

And in the Devtools network tab

Devtools network tab

I've tried the following link Issues with Axios catch method from Laracast

how to display the errors in .catch coming from an api on frontend

And some others solution,but all of them didn't solve my problem. Before using async-await pattern i used axios.post('url',data).then(res=>...).catch(err=>...)

When i use postman,http status is still 422 but the error object is returned,so with postman everything goes fine but not in the browser

Postman test

How can i solve this problem?

Christian LSANGOLA
  • 2,947
  • 4
  • 22
  • 36

4 Answers4

0

Laravel returns the HTTP 422 - Unprocessable Entity when the validations you set fail. In your case I would take a closer look at the data you're posting to the server and manually check if it passes the validation cases you wrote.

To get the exact fields that are causing the error you need to handle this in your code, like this for example:

$validator = Validator::make($data, $rules);

if ($validator->fails()) {

  // 500 is the HTTP Status Code you want to return.   
  // This should also throw you in the catch branch of your front-end code
  return response()->json(['errors'=>$validator->errors()], 500);

}

In your code the $data variable from the register function should be checked if it fails validation and return the error

VladNeacsu
  • 1,268
  • 16
  • 33
  • If there were problems with data that i'm sending i would also have problem in cas which the validation succedes.When validation is succeded the user data is return and the data is stored into the database – Christian LSANGOLA Mar 07 '19 at 09:17
  • @jochri3 Are you saying you're still getting the `HTTP 422` but the data is still saved in the database? – VladNeacsu Mar 07 '19 at 09:20
  • No i've said in case of `HTTP 422` data is not stored into the `database`,but i cannot access `error object` in the `console`.But when my form is good,every filed filled data is stored and `user object` is return and i ca n access it in the `console` – Christian LSANGOLA Mar 07 '19 at 09:25
  • I'm sorry, I have a hard time understanding your spelling, but from what I get this still seems like a validation error. Can you post a JSON or a screenshot of the data being sent to the server? – VladNeacsu Mar 07 '19 at 09:27
  • `{email: "", password: "", password_confirmation: "", fname: "", lname:"",fname:"",lname:"",city:""} ` – Christian LSANGOLA Mar 07 '19 at 09:39
  • @jochri3 They cannot be empty as they have 'required' validation role! – Ahmed Nasr Mar 07 '19 at 09:44
  • I would like to customize the registration in case of errors,that whey i should have errors message returned so that i can display them in the form – Christian LSANGOLA Mar 07 '19 at 10:01
  • Ok, now that makes sense. I think you should rephrase your question a bit as it wasn't clear that this is what you wanted to achieve. – VladNeacsu Mar 07 '19 at 10:03
  • Now it works,i can access the errors,but the errors are catched in the `try` bloc,not in `catch` – Christian LSANGOLA Mar 07 '19 at 10:27
  • Yes, that's because of the `response()->json()` method. You can read more on that here: https://laravel.com/docs/5.7/responses If you want to return an error you can use `return response()->json(['hello' => $value], 500); ` where `500` is the HTTP Status Code you want your api to return – VladNeacsu Mar 07 '19 at 10:48
0

This is because err will return the toString() method when accessed directly, but has properties:

err.response.data will have what you're looking for.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
0

When Axios throws an error, the HTTP response can be found in error.response. Validation errors will be in the errors key, so you can access validation errors like this:

axios.post(someUrl, someData)
    .then(response => {
        // Successful response
    })
    .catch(error => {
        let errors = error.response.data.errors;
    });
Martin Bean
  • 38,379
  • 25
  • 128
  • 201
0

When there's an HTTP error (e.g. a response code between 400 and 599) axios returns an axios error response and in the repository documentation under error handling it indicates that you can access the actual response using error.response.data. For example:

 try {
       const res=await axios.post('api/register',
       {
           email:this.form.email,
           password:this.form.password,
           password_confirmation:this.form.password_confirmation,
           fname:this.form.fname,
           lname:this.form.lname,
           city:this.form.city
       });
       //Une fois inscrit,il est redirige vers la page de login
       this.$router.push({path:'/login'});
       console.log("My data : ",res.data);
   }catch(err){
       if (err.response && err.response.status === 422) {
           if (err.response.data.errors.fname) {
              console.log('First name errors: '+ err.response.data.errors.fname.join(','));
           } 

           // and so on

       }
   }
apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • This line `if (err.response && err.response.status === 422)` checks if `err.response` is defined before checking `err.response.status` . If `err.response` is undefined then that means you don't actually have an HTTP error but rather another kind of error. In your initially shared console there's also the line `Cannot read property 'data' of undefined` which is an error but not an HTTP error so it would also be caught in the `catch` block so you should try to differentiate between the two cases – apokryfos Mar 07 '19 at 10:02