我使用来自此源的基于令牌的身份验证创建了一个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令牌是否与数据库中的相同,并且它完全相同 . 所以它不应该是因为一个坏令牌 .