如何显示来自前端 api 的 .catch 中的错误

IT技术 laravel reactjs axios
2021-05-16 15:34:49

我正在使用laravel构建一个项目,这很简单,api我使用 Passport 构建,并且在frontend我使用react 时一切正常,只是我无法在 .catch 函数中捕获错误消息,我可以在网络选项卡中看到错误我的浏览器,但我不知道如何显示它们。

这是我的 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'])
        ]);
   }
}

这就是我使用 axios 使用 api 的方式:

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);
        });
    }
}

这是控制台日志

在此处输入图片说明

这是我浏览器网络选项卡中的响应

在此处输入图片说明

  • 如果您有任何问题,请告诉我。
  • 任何帮助将被赞赏
2个回答

更改以下代码行。

.catch((error) =>  {
            console.log(error.response);
        });
.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;
    });

请检查以下代码

https://github.com/johibkhan2/react-redux-singlePageApp/blob/master/app/api/phone-api.js