首页 > 解决方案 > Axios 在调用 Laravel API 时在反应中捕获响应

问题描述

嗨,我正在为后端使用 Laravel API,并在 React 中使用 Redux 进行登录。好吧,我调用了 API,我希望 laravel API 传递正在发生的事情的精确错误,例如用户不存在。问题是当我想在使用 axios 进行的调用的捕获部分中访问消息时

Laravel 登录部分

public function login(Request $request){
        
        $loginData = $request->validate([
            'name' => 'required',
            'password' => 'required'
        ]);

        if (!auth()->attempt($loginData)) {
            return response(["message" => "I want to acces this message in the catch part of Axios"], 401);
        }

        $accessToken = auth()->user()->createToken('authToken')->accessToken;

        return response(['user' => auth()->user(), 'access_token' => $accessToken]);

    }

使用 axios 响应调用

Axios({
                method: 'post',
                url: '/login',
                data: {
                  name: name,
                  password: password,
                }
            }).then(function (response) {
                dispatch(authSuccess(response.data.access_token, response.data.user.id));
            })
            .catch(function (response) {
                console.log(response)
            });

我在 Web 控制台中得到的响应

xhr.js:177 POST http://127.0.0.1:8000/api/login 401(未经授权)

并且我想获取我在 Laravel API 中传递的消息(“我想在 Axios 的 catch 部分中访问此消息”)

标签: phpreactjslaravel

解决方案


您可以在此处使用从服务器接收到的错误对象,这是获取进一步处理错误对象的示例代码:

 Axios({
          method: 'post',
           url: '/login',
          data: {
             name: name,
             password: password,
                }
            }).then(function (response) {
                dispatch(authSuccess(response.data.access_token, response.data.user.id));
            })
             .catch(err => { 
        if (err.response) { 
          // client received an error response (5xx, 4xx)
        } else if (err.request) { 
          // client never received a response, or request never left 
        } else { 
          // anything else 
        } 
      })

推荐阅读