How do you force a JSON response on every response in Laravel?

后端 未结 6 2078
面向向阳花
面向向阳花 2021-02-13 14:31

I\'m trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:

return Respo         


        
6条回答
  •  庸人自扰
    2021-02-13 15:27

    I've used several mixed solutions also mentioned here to solve everything a bit more dynamic. The reason was here to always reply on every request below "/api" with a json response.

    1. Create a Middleware to force JSON Output in app/Http/Middleware/ForceJsonResponse.php
    headers->set('Accept', 'application/json');
    
            return $next($request);
        }
    }
    
    
    1. Add this new middleware on TOP of the api array in app/Http/Kernel.php
        protected $middlewareGroups = [
            ...
    
            'api' => [
                \App\Http\Middleware\ForceJsonResponse::class,
                'throttle:api',
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],
    
            ...
        ];
    
    
    1. Overwrite the render method of the Exception handler that all exceptions also response with JSON app/Exceptions/Handler.php
      namespace App\Exceptions;
    
      use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    + use Throwable;
    
      class Handler extends ExceptionHandler
      {
    
         ...
    
    
    +    /**
    +     * Render an exception into an HTTP response.
    +     *
    +     * @param  \Illuminate\Http\Request  $request
    +     * @param  \Throwable $e
    +     * @return \Illuminate\Http\Response
    +     */
    +    public function render($request, Throwable $e)
    +    {
    +        // Force to application/json rendering on API calls
    +        if ($request->is('api*')) {
    +            // set Accept request header to application/json
    +            $request->headers->set('Accept', 'application/json');
    +        }
    +
    +        // Default to the parent class' implementation of handler
    +        return parent::render($request, $e);
    +    }
    
    }
    

提交回复
热议问题