mardi 26 février 2019

Axios unbale to catch error when server sends 422 in try-catch bloc

I'm using axios for my HTTP with Vue.js.But when I do the ajax call, everything goes well when server sends back response data with 200 success. But when there is errors,server does not execute the catch bloc. Here is my ajax call in Vue.js

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',this.form);
               console.log("Ba donnees : ",res.data);
           }catch(err){
               console.log("Erreeer",err.response);
           }
        }
    }
}

And here is my register controller:

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);

    }

When everything goes fine, I get the expected result of my try but in case of POST http://localhost:5000/api/register 422 (Unprocessable Entity) the is trying to log the statement in try.

But when I go in the network tab, I see the returned error JSON like this

{"message":"The given data was invalid.","errors":{"fname":["The fname field is required."],"lname":["The lname field is required."],"city":["The city field is required."],"email":["The email field is required."],"password":["The password field is required."]}}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire