如果我使用 API 路由,如何让我的中间件响应 json object

How can I make my middleware respond with a json object if I use an API route

我正在使用 Laravel 构建我的第一个 API,并且我正在使用 JWT 进行身份验证。我还不太了解守卫,但我想我设法守住了我的用户 class。因此,当我尝试访问我的 UserController 中的路由时,它会受到保护,如果用户未通过身份验证,则会调用 Authenticate 中间件。问题是,当我尝试通过 Postman 使用 API 路由时,出现以下错误

ErrorException: Header 不能包含多个 header,在文件

中检测到新行

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    protected function redirectTo($request)
    {
         if (!$request->expectsJson()) {
            return response()->json(['message' => 'Unauthorized'], 403);
         }
    }
}

api.php

<?php
use Illuminate\Support\Facades\Route;

Route::post('register', 'AuthController@register');
Route::get('user/{id}', 'UserController@index');

试试这个

Route::group(['middleware' => 'auth:api'], function(){
// Put your authenticated routes here
});

您可以使用:

abort(response()->json('Unauthorized', 403));