I have a method that captures the information sent by the vue view (Profile.vue) through a PUT generated by Axios, the problem lies in the following, when the data is updated (through the myProfile method of the UserController controller), axios captures the information of the json return from the method, and the success message is displayed, but when there is an error, Axios does not capture the error json information and tells me the following:
Uncaught (in promise) TypeError: Cannot read property 'status' of undefined
I understand that you are claiming me for the variables that I have in the Axios catch that do not have information
The code for myProfile is as follows:
$profile = User::find(Auth::user()->id);
$profile->firstname = $request->firstname;
$profile->lastname = $request->lastname;
$profile->gender = $request->gender;
$profile->description = $request->description;
if($profile->update())
{
return response()->json([
'status' => 'Muy bien!',
'msg' => 'Datos actualizados correctamente.',
'cod' => 201
]);
}
else{
return response()->json([
'status' => 'Ocurrio un error!',
'msg' => 'Ocurrio un error al actualizar la información.',
'cod' => 400
]);
}
Axios section of Profile.vue
axios.put('/dashboard/profile', value)
.then((response) => {
let title = response.data.status;
let body = response.data.msg;
this.displayNotificationSuccess(title, body);
})
.catch((response) => {
let title = response.data.status;
let body = response.data.msg;
this.displayNotificationError(title,body);
})
As I mentioned before, when there is success in the controller, Axios reads and displays the json message, when there is an error, it does not.
Where am I failing that Axios cannot display the json error message coming from the controller?
I use Laravel 5.6, Vuejs 2 and Axios
The problem is that you are not passing the
status code
to your response from Laravel so it will always get a status200
ofOK
, it is for this reason that it will never enter thecatch
from axios .To solve the status code, it is passed as a second parameter to the function
->json()
in the following way.The complete list of codes are in
Symfony\Component\HttpFoundation\Response
So your solution would be.
Laravel
Axios