我尝试在我的 Laravel + Vue SPA 中实现 JWT Auth。
在我的 Controller 中,我检查凭据,例如
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(
[
'error' => 'Invalid Credentials',
], 401
);
}
} catch (JWTException $e) {
return response()->json(
[
'error' => 'Could not create token!',
]
);
}
return response()->json(
[
'token' => $token,
]
);
我的 API 调用如下所示:
axios.post('/api/user/signin', payload)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
如果我通过 payload
传递有效凭据,我会在 then
block 中获得 token ,并可以将其记录在控制台中。
如果我传递无效凭据,我会在控制台中收到错误消息:
Error: Request failed with status code 401 at createError (app.js:10562) at settle (app.js:21378) at XMLHttpRequest.handleLoad (app.js:10401)
如何收到“无效凭据”错误?如果我从响应中删除状态代码或将其设置为 200,我会收到错误“无效凭据”。
最佳答案
您可以使用错误的响应
键。以获得响应。
axios.post('/api/user/signin', payload)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err.response)
})
检查这里:https://github.com/mzabriskie/axios/blob/master/UPGRADE_GUIDE.md#012x---0130
关于javascript - Laravel 与 JWT Auth : Get error message with status code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588753/