1. 程式人生 > >Laravel API 返回 JSON 格式的響應

Laravel API 返回 JSON 格式的響應

Passport 做的 API 認證,用 Postman 測試 API 時,在沒有獲取 token 的情況下訪問介面,會自動跳轉到登入介面,這顯然不是我想要的,雖然可以設定 Headers 解決,但是我希望即使在瀏覽器端測試 API ,也是返回 json 格式的錯誤資訊,而不是跳轉到登入介面。

下面是解決辦法:

1、新建中介軟體 JsonResponse

php artisan make:middleware JsonResponse

2、編輯 app/Http/Middleware/JsonResponse 檔案:

public function handle($request, Closure $next)
    {
        if ($request->is('api/*')){
            $request->headers->set('Accept', 'application/json');
        }
        return $next($request);
    }

3、把 JsonResponse 新增到 Kernel 中,編輯 app/Http/Kernel:

protected $middleware = [
		......
		
        //Application Middleware
        \App\Http\Middleware\JsonResponse::class,
    ];

再次訪問介面,會有如下響應:

{
  "message": "Unauthenticated."
}

https://www.hellocode.wang/article/laravel-api-json-response-VWbZXsR6