Using laravel5.8. 同时使用web和API(Token Gaurd(。
使用无效api_token参数的 API 调用时,收到错误路由:未定义登录。 我想要 JSON 格式的响应。 在论坛中阅读我需要在应用程序\异常\处理程序中使用以下方式.php并且它可以工作。 我对某些路径有网络保护。 我希望 route:login 在它是 Web 保护时工作,并在使用 api guard 时返回 json 响应。如何在 Laravel 5.8 中做到这一点?
public function render($request, Exception $exception)
{
// dd(get_class($exception));
// return parent::render($request, $exception);
return response()->json(
[
'errors' => [
'status' => 401,
'message' => 'Unauthenticated',
]
], 401
);
}
我将逻辑放在unauthenticated
函数中,结合expectsJson()
应该可以解决您的问题
// in appExceptionsHandler.php
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['status' => 401,'message' => 'Unauthenticated.'], 401);
}
return redirect()->guest('/');
}