我从以下来源使用基于令牌的身份验证制作了Laravel / React应用程序:https://medium.com/@Gbxnga/token-based-authentication-with-react-and-laravel-restful-api-83f16581e85但是,每次我尝试从受保护的资源中获取数据时,都会得到HTML作为响应而不是JSON。
我用他们的中间件保护了我的API调用。那是jwtMiddleware:
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::toUser($request->input('token'));
} catch (Exception $e) {
if ($e instanceof TokenInvalidException){
// return $next($request);
return response()->json(['error'=>'Token is Invalid']);
}else if ($e instanceof TokenExpiredException){
// return $next($request);
return response()->json(['error'=>'Token is Expired']);
}else{
// return $next($request);
return response()->json(['error'=>'Something is wrong']);
}
}
return $next($request);
}
API:
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
$response->header('Access-Control-Allow-Origin', '*');
//add more headers here
return $response;
}
在我的API路由中,我拥有受保护的API调用:
Route::group(['middleware' => ['jwt.auth','api-header']], function () {
// all routes to protected resources are registered here
Route::get('users/list', function(){
$users = App\User::all();
$response = ['success'=>true, 'data'=>$users];
return response()->json($response, 201);
});
});
在此功能中,我尝试像在网站上一样获取用户列表:
componentDidMount() {
const token = localStorage.getItem('jwtToken');
axios.get(`http://127.0.0.1:8000/api/user/list?token=${token}`)
.then(response => {
console.log(response);
return response;
})
.then(json => {
if (json.data.success) {
alert("Login Successful!");
} else alert("Login Failed!");
})
.catch(error => {
alert(`An Error Occured! ${error}`);
});
}
但是我的回应给了我这个
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#db5945">
<meta name="csrf-token" content="bxHaQn6jmnsoAkW7OQ8OVY9pPVy9VgpPJurFyzYS">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<link rel="manifest" href="manifest.json" >
<link href="/css/app.css" rel="stylesheet" type="text/css">
<link href="/css/all.css" rel="stylesheet" type="text/css">
<title>Application Name</title>
</head>
<body>
<div id="root"></div>
<script src="/js/app.js"></script>
</body>
</html>
有人可以向我解释为什么我将HTML页面作为响应而不是我发回的JSON响应吗?登录时,我检查了JWT Auth令牌是否与数据库中的令牌相同,并且是否完全相同。因此,这不应该是因为令牌不正确。