If your are using laravel for API and vue/Nuxtjs for frontend and axios for send data to API....
This type of errors can be faced for laravel validation error sending not in correct way using try{} catch(){} block or receiving errors by axios not in correct way to using try() catch(){} block.
Here, try catch block using for error handling.
If your API routes called the public function its name "register()", so your function inside your controller have to like following...(I am using laravel-8 for API)
public function register(Request $request) {
try {
$fields = $request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed',
]);
$user = User::create([
'name' => $fields['name'],
'email' => $fields['email'],
'password' => bcrypt($fields['password'])
]);
$token = $user->createToken('myapptoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response()->json($response, 200);
} catch(ValidationException $e) {
return response()->json([
'status' => 'error',
'msg' => 'error',
'errors' => $e->errors()
], 422);
}
}
and Frontend Nuxt or vue methods name is "registerNewUser()" so, codes can be following for error handling...
async registerNewUser() {
try {
let data = {
name : this.name.trim(),
email : this.email.trim(),
password : this.password.trim(),
password_confirmation : this.password_confirmation.trim(),
};
let headers = {
headers: {
'Accept': 'application/json',
}
};
await this.$axios
.post("/api/register", data, headers)
.then((response) => {
console.log("response", response);
if(response) {
// console.log(response)
} else {
}
});
} catch(err) {
// here we are receiving validation errors
console.log("Err == ", err.response);
console.log(err.response.data.errors);
}
}
You are receiving response inside axios then block or receive error inside catch block using err.response
Here,
let data = {
name : this.name.trim(),
email : this.email.trim(),
password : this.password.trim(),
password_confirmation : this.password_confirmation.trim(),
};
Given codes is for data of Nuxtjs or vuejs. If not know that you can using like following data or any other data...
let data = {
name : 'Kallol',
email : 'kallolray94@gmail.com',
password : '123456',
password_confirmation : '123456',
};