【发布时间】:2020-04-28 19:20:04
【问题描述】:
我正在做一个 react-laravel 项目,我正在尝试使用中间件保护仪表板路由,这是来自中间件的代码
public function handle($request, Closure $next)
{
$apiToken = $request->bearerToken();
$isAuthenticated = User::where('api_token', $apiToken)
->where('is_admin', true)
->first();
if(!$isAuthenticated) {
return redirect('/');
}
return $next($request);
}
现在的问题是,如果用户未通过身份验证,中间件不会重定向到所需的路由,而是将 html 页面作为响应中的文本返回,如下所示。Response in case of of not authenticated user
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<meta name="description" content="Web site created using create-react-app"/>
<link rel="stylesheet" href="http://localhost/css/app.css">
<title>Some Title Here</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="http://localhost/js/app.js"></script>
</body>
</html>
我尝试过使用
return redirect()->route('/');
但遗憾的是它也不起作用。
我也尝试使用
抛出 401 异常abort(401)
并在异常处理程序中捕获它并从那里重定向(就像我对 404 和 500 异常所做的那样,我已成功重定向)但这不起作用,我收到与发送的页面相同的响应消息响应中的文本,所以问题可能是从中间件重定向,有人可以帮我找到问题吗?
【问题讨论】:
标签: php reactjs laravel redirect middleware