laravelvue.jsvuejs3vee-validate

axios request is not giving response or errors


i am using vue js with vee validate on frontend and laravel 10 on backend and i trying to hit my register api , i want to show the validation errors that are returned from the backend api , the response was in this format

{
    "status": "failed",
    "message": "Validation Error!",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "user_name": [
            "The user name field is required."
        ],
        "email": [
            "The email has already been taken."
        ],
        "password": [
            "The password field must be at least 8 characters."
        ]
    }
}

i have tried multiple solutions from the internet but fail to understand why it is behaving like this

const onSubmit = handleSubmit(async (values) => {
     await axios.post("/register",{
        username: values.username,
        email: values.email,
        password: values.password
      })
.then(res=>{
    console.log(res);
})
.catch(err=>{
    console.log(err);
});

//       
});

i have also tried with try catch but it always return response as undefined and whenever i hit the api and it returns error , it does not enter the catch block

this is my backend code

 $validate = Validator::make($request->all(), [
            'name' => 'required|string|max:250',
            'user_name' => 'required|string|max:50|unique:users,user_name',
            'email' => 'required|string|email:rfc,dns|max:250|unique:users,email',
            'password' => 'required|string|min:8'
        ]);

        if($validate->fails()){
            $response = [
                'status' => 'failed',
                'message' => 'Validation Error!',
                'errors' => $validate->errors(),
            ];
            return response()->json($response, 403);
            //throw new \Illuminate\Validation\ValidationException($validate);
        }

any help will be appreciated


Solution

  • saw many posts and threads related to this issue , some said it was due to the CORS issue , others gave their own answers ,

    however i was able to solve this one adding a

     var instance = axios.create({
            validateStatus: function (status) {
                return status == 201;
            }
        });
    

    then did the request in this way ,

      instance.post('/register', values)
        .then( 
       (response) => { 
        console.log(response);
            Swal.fire({
              icon: 'success',
              title: 'Success!',
              text: 'Registeration Completed Successfully',
            });
            modalClose();
          
       },
       (error) => {
          console.log(error);
          actions.setErrors(error.response.data.error);
        }
    

    this way i was able to get the error in my error block and the 201 as response

    the detail thread was found on: https://github.com/axios/axios/issues/960