承诺链末尾的 Laravel Sanctum SPA catch() 不会捕获错误



我正在尝试使用Laravel, React和Sanctum SPA认证做一个简单的登录页面。我的问题是,即使我用catch()结束我的承诺链,我也会从axios承诺中得到一个未捕获的错误,而且我对Laravel或axios的了解几乎不够,无法找出原因。

控制台:

app.js:197 POST http://localhost:8000/api/login 403 (Forbidden)
app.js:607 Uncaught (in promise) Error: Request failed with status code 403
at createError (app.js:607)
at settle (app.js:878)
at XMLHttpRequest.handleLoad (app.js:82)

请求:

api.get('/sanctum/csrf-cookie').then(() => {
api.post('/api/login', {
name: username,
password: password
}
).then((response) => {
//Works if I enter the correct credentials
console.log('works')
})
}).catch(error => {
//Won't catch the error if I enter wrong credentials
setError('error')
})

Laravel控制器:

public function logIn(Request $request) {
$credentials = $request->only('name', 'password');
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return response()->json([], 204);
}
return response()->json([], 403);
}

我发现的一个解决方法是不返回403,而是返回带有错误消息的200,并相应地分支代码。但我发现这相当令人困惑,因为我看到的几个Sanctum SPA身份验证示例使用了原始方式。

我强烈建议你像下面这样把你的承诺串起来:

api.get('/sanctum/csrf-cookie')
.then(() => api.post('/api/login', { 
name: username,
password: password}))
.then((response) => {
console.log('works')
}).catch(error => {
//Won't catch the error if I enter wrong credentials
setError('error')
})

注意api.post的结果是如何返回的,then是在外部then之后链接的,而不是在回调中。这将允许catch捕获来自api.getapi.post的任何错误

最新更新