php - 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 部分中访问此消息”)
解决方案
您可以在此处使用从服务器接收到的错误对象,这是获取进一步处理错误对象的示例代码:
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
}
})
推荐阅读
- universe - 虚拟属性中的内联提示?
- vim - ctags 无法找到包含连字符的变量
- elasticsearch - 默认情况下,在文本字段上禁用 Fielddata 设置 fielddata=true
- python - 使用 pyinstaller 时如何修复无效模块
- python - 由于形状不正确,无法在 Keras 中拟合数据
- css - 如何将搜索图标移动到标题的左侧和右侧的菜单
- bash - 除了移动到每个目录之外,是否有 git 或 bash 方式来提取多个 git 存储库?
- react-native - 下载开放街道地图的tiles.png
- kubernetes - 在没有 systemd 的 debian 拉伸服务器上安装 kubernetes
- gitlab - 如何增加本地 Gitlab 的最大工件大小