I'm trying to send some form data to my backend, but validation with Laravel isn't returning errors with 422 status.
Axios
Simple axios post request to a URL and looking to get a response back if we catch an error during request cycle.
axios.post(this.formURL, formData)
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
})
Laravel
I have set up Laravel Validation to validate some form inputs and return 422 if validation fails.
try {
$this->validate(request(), [
'chapter_id' => 'required',
'brother_id' => 'required'
]);
Minute::forceCreate(request());
return response()->json([
'status' => 'success',
'message' => 'Minute Created',
], 201);
}
catch (ValidationException $exception) {
return response()->json([
'status' => 'error',
'message' => 'Error',
'errors' => $exception->errors(),
], 422);
}
Response
A response is given, but I get undefined in console when I try to console it out:
{
"status":"error",
"message":"Error",
"errors":{
"brother_id":[
"The brother_id field is required."
],
"chapter_id":[
"The chapter_id field is required."
]
}
}
I have come across this issue here https://github.com/axios/axios/issues/960#issuecomment-398269712 but was unable to get past this using their resolution methods. Has anyone come across this issue before? Could this be authentication relation (not likely), that's the last thing I implemented.
Resolution
This issue resolved. While implementing axios interceptor to catch authentication errors, I did not return the errors back to the Promise.
axios.interceptors.response.use(null, (error) => {
if ( error.response.status == 401 ) {
store.commit('logout')
router.push('/login')
}
return Promise.reject(error)
})
return Promise.reject(error)
was missing. Thanks for your help guys!