如何使用中间件向响应添加标头?

时间:2015-02-10 09:43:52

标签: laravel laravel-5

我无法弄清楚如何将标头添加到中间件的响应中。我同时使用了->header(...)->headers->set(...),但两者都有错误。那你怎么做的?

首先我尝试了

public function handle($request, Closure $next) {
    $response = $next($request);

    $response->headers->set('refresh', '5;url=' . route('foo'));

    return $response;
}

Illuminate\Http\Middleware\FrameGuard.php中的相同,但是给出了

  

在非对象

上调用成员函数set()

其次我尝试了

public function handle($request, Closure $next) {
    $response = $next($request);

    $response->header('refresh', '5;url=' . route('foo'));

    return $response;
}

但是这给了

  

视图中不存在方法[标题]。

那么如何从中间件添加标头?

3 个答案:

答案 0 :(得分:8)

我使用response帮助器解决了这个问题。

use Illuminate\Http\RedirectResponse;

$response = $next($request);
$response = $response instanceof RedirectResponse ? $response : response($response);

return $response->header('refresh', '5;url=' . route('foo'));

我所有的其他中间件似乎都运行正常,所以我想这很好。

答案 1 :(得分:6)

以下是在 Laravel 5.0 中测试的解决方案,用于将标头附加到路径

创建中间件文件app/Http/Middleware/API.php

<?php namespace App\Http\Middleware;
use Closure;
class API {

    public function handle($request, Closure $next)
    {

            $response = $next($request);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
            $response->header('Access-Control-Allow-Origin', '*');
            //add more headers here
            return $response;
        }
}

通过将这些行添加到/app/Http/Kernel.php

,将中间件添加到内核文件中
protected $middleware = [
    //... some middleware here already 
    '\App\Http\Middleware\API',// <<< add this line if you wish to apply globally
];
protected $routeMiddleware = [
    //... some routeMiddleware here already 
    'api' => '\App\Http\Middleware\API', // <<< add this line if you wish to apply to your application only
];

在路线档案/app/Http/routes.php

中对路线进行分组
Route::group(['middleware' => 'api'], function () {
    Route::get('api', 'ApiController@index');
    //other routes 
});

答案 2 :(得分:2)

它也可以工作,只需添加到中间件软件中即可:


    public function handle($request, Closure $next)
{
    $request->headers->set('accept', 'application/json', true);

    return $next($request);
}