【问题标题】:how to display the errors in .catch coming from an api on frontend如何在 .catch 中显示来自前端 api 的错误
【发布时间】:2017-12-22 18:37:57
【问题描述】:

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

这是我的用户控制器

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

这是控制台日志

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

  • 如果您有任何问题,请告诉我。
  • 我们将不胜感激任何帮助

【问题讨论】:

    标签: laravel reactjs axios


    【解决方案1】:

    更改以下代码行。

    .catch((error) =>  {
                console.log(error.response);
            });
    

    【讨论】:

    • 谢谢@imran 我已经调试了一个多小时。
    • @AmrAly 欢迎
    【解决方案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;
        });
    

    请检查以下代码

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

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2020-09-17
      • 2019-04-18
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多