如何为路由组中的所有请求设置标头 [英] How to set header for all requests in route group
问题描述
我正在使用Laravel 5.4创建一个API,并且一切正常.我已经使用了以下中间件=> auth:api
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 :
- 授权:承载api_token
- Accept:application/json
当api_token无效时,将执行Handler类的未经身份验证的功能. laravel返回的默认响应是
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
但是,当未设置Accept标头时,laravel默认返回一个视图.但是使用API时,视图是不可接受的.
But when the Accept header is not set, laravel returns a view by default. But with an API, views are not acceptable.
对于路由组中的每个路由请求,我如何强制laravel检查是否为正确的值设置了Accept报头(在这种情况下,该值必须为=> accept/json)?
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?
类似的东西:
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->header('Accept' => 'application/json') //this
->group(base_path('routes/api.php'));
}
或
Route::group(['middleware' => 'auth:api',
'headers' => ['Accept' => 'application/json']
], function(){
Route::get('URIValue', ControllerName@action) //Example
});
推荐答案
您可以为此创建一个中间件.
You can create a middleware for that.
您将检查并强制执行Accept标头,以便Laravel无论如何都将输出json.
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);
}
}
然后在您的App\Http\Kernel
中,您可以将中间件添加到您的api组中.然后,无需手动将其添加到路由/路由组中.
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.
您还可以添加一个中间件来强制执行json,无论如何...
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屋!