How to set header for all requests in route group

后端 未结 2 1587
渐次进展
渐次进展 2021-01-12 14:34

I\'m creating an API with Laravel 5.4 and it all works well. I\'ve used the following middleware => auth:api like this

Route::group([\'middleware\' => \'a         


        
相关标签:
2条回答
  • 2021-01-12 15:03

    You can use simple middleware like this

    class OnlyAcceptJsonMiddleware
    {
        /**
         * We only accept json
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
           // Verify if request is JSON
            if (!$request->expectsJson()) {
                return response(['message' => 'Only JSON requests are allowed'], 406);
            }
    
            return $next($request);
        }
    }
    

    And in your App\Http\Kernel you can add the middleware to you api group or any group that you wanna use.

    0 讨论(0)
  • 2021-01-12 15:09

    You can create a middleware for that.

    You'll have check and enforce the Accept header so Laravel will output json no matter what..

    class WeWantJson
    {
        /**
         * We only accept json
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $acceptHeader = $request->header('Accept');
            if ($acceptHeader != 'application/json') {
                return response()->json([], 400);
            }
    
            return $next($request);
        }
    }
    

    And in your App\Http\Kernel you can add the middleware to you api group. Then there's no need to manually add it in the routes/routegroups.


    Edit:

    You could also add a middleware to enforce json no matter what...

    class EnforceJson
    {
        /**
         * Enforce json
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $request->headers->set('Accept', 'application/json');
    
            return $next($request);
        }
    }
    
    0 讨论(0)
提交回复
热议问题