如何为路由组中的所有请求设置标头 [英] How to set header for all requests in route group

查看:33
本文介绍了如何为路由组中的所有请求设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Laravel 5.4 创建 API,并且一切正常.我使用了以下中间件 => auth:api 像这样

Route::group(['middleware' => 'auth:api'], function(){Route::get('URIValue', ControllerName@action)//示例});

我已经用邮递员测试过,当请求标头包含以下键和值时,它运行良好:

  • 授权:不记名api_token
  • 接受:应用程序/json

当 api_token 无效时,执行 Handler 类的未认证函数.laravel 返回的默认响应是

'error' =>'Unauthenticated'//JSON 格式

但是当没有设置 Accept 头时,laravel 默认返回一个视图.但是对于 API,视图是不可接受的.

如何强制 laravel 为路由组中的路由的每个请求检查 Accept 标头是否设置了正确的值(在这种情况下,该值必须是 => accept/json)?

类似于:

受保护的函数 mapApiRoutes(){路线::前缀('api')-> 中间件('api')-> 命名空间($this->命名空间)->header('Accept' => 'application/json')//this-> group(base_path('routes/api.php'));}

Route::group(['middleware' => 'auth:api','标题' =>['接受' =>'应用程序/json']], 功能(){Route::get('URIValue', ControllerName@action)//示例});

解决方案

您可以为此创建一个中间件.

您将检查并强制执行 Accept 标头,以便 Laravel 无论如何都会输出 json..

class WeWantJson{/*** 我们只接受 json** @param \Illuminate\Http\Request $request* @param \Closure $next* @return 混合*/公共函数句柄($request, Closure $next){$acceptHeader = $request->header('Accept');if ($acceptHeader != 'application/json') {返回响应()-> json([], 400);}返回 $next($request);}}

并且在您的 App\Http\Kernel 中,您可以将中间件添加到您的 api 组中.这样就不需要在路由/路由组中手动添加了.

<小时>

你也可以添加一个中间件来强制执行 json...

class EnforceJson{/*** 强制 json** @param \Illuminate\Http\Request $request* @param \Closure $next* @return 混合*/公共函数句柄($request, Closure $next){$request->headers->set('Accept', 'application/json');返回 $next($request);}}

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' => 'auth:api'], function(){ 
    Route::get('URIValue', ControllerName@action) //Example
});

I've tested it with postman and it works well when the request header contains the following keys and values :

  • Authorization:Bearer api_token
  • Accept:application/json

When the api_token is invalid the unauthenticated function of the Handler class is executed. The default response that laravel returns is

'error' => 'Unauthenticated' // in JSON format

But when the Accept header is not set, laravel returns a view by default. But with an API, views are not acceptable.

How can I force laravel to check that the Accept header is set with the right value (in this case the value must be => accept/json) for every single request for the routes that are in the route group?

Something like:

protected function mapApiRoutes()
{
    Route::prefix('api')
          ->middleware('api')
          ->namespace($this->namespace)
          ->header('Accept' => 'application/json') //this
          ->group(base_path('routes/api.php'));
}

or

Route::group(['middleware'  => 'auth:api', 
              'headers'     => ['Accept' => 'application/json']
             ], function(){ 
                    Route::get('URIValue', ControllerName@action) //Example
             });

解决方案

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);
    }
}

这篇关于如何为路由组中的所有请求设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆