问题
I am building a project using laravel which is simple api i have built using passport and on the frontend i am using react everything works fine except that i can't catch the error messages in the .catch function i can see the errors in the network tab of my browser but i cant figure out how to display them.
here is my UserController
class UserController extends Controller
{
public function create(Request $request)
{
$data = $request->only('name', 'email', 'password');
$validator = Validator::make($data, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return response()->json(['errors'=>$validator->errors()], 422);
}
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
}
}
and this how i consume the api using axios:
export function signupUser({ name, email, password }) {
return function(dispatch) {
axios.post(`${ROOT_URL}/api/signup`, {name, email, password})
.then(response => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.access_token);
browserHistory.push('/feature');
})
.catch((error) => {
// console.log(error);
});
}
}
and here is the console log
and here is the response in the network tab of my browser
- If you have any question please let me know.
- Any help will be appreicated
回答1:
Change the following lines of code.
.catch((error) => {
console.log(error.response);
});
回答2:
.catch(function (error) {
if (error.response) {
// The request was made, but the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
// Something happened in setting up the request that triggered an
console.log('Error', error.message);
}
return error;
});
Please check the below code
https://github.com/johibkhan2/react-redux-singlePageApp/blob/master/app/api/phone-api.js
来源:https://stackoverflow.com/questions/45157543/how-to-display-the-errors-in-catch-coming-from-an-api-on-frontend