我正在使用Sanctum创建API,并且工作正常,可以列出用户,更新,存储等。
我添加了中间件auth:sanctum和传递令牌,并添加了中间件中的SecureFrontendRequestsAreStateful,如文档中所述。
使用无效令牌无效,我将重定向到登录名。
但是,验证失败时会发生问题,我正在使用表单请求,但是即使在控制器验证中,失败时也会重定向到主页。
我正在使用Postman来测试API,并且如果禁用“自动跟随重定向”,则可以看到setTargetUrl使用的html页面进行重定向,
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="0;url='%1$s'" />
<title>Redirecting to %1$s</title>
</head>
<body>
Redirecting to <a href="%1$s">%1$s</a>.
</body>
</html>
它指向我的家。
我尝试从哪里检查此重定向,但无法理解。而且不是通过RedirectIfAuthenticated。
我希望看到带有错误消息的JSON响应。
即使Laravel文档的示例代码用于创建令牌,如果验证失败,也存在以下重定向:
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
并且仅当验证失败但没有重定向时,所以我认为验证才进行重定向,但由于没有重定向,因此它将重定向到主目录。
谢谢
更新
我找到了一种解决方法,但不确定这是否是唯一方法。
添加try catch,我可以显示验证错误而无需重定向。
try {
$data = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required',
]);
} catch(\Illuminate\Validation\ValidationException $e) {
return response()->json([
'message' => $e->getMessage()
]);
}
答案 0 :(得分:2)
您可能希望将Accept
标头作为application/json
发送,以便服务器知道您正在接受JSON。这是异常处理程序确定如何从验证异常返回响应的一部分。