如何使用中间件将 headers 添加到响应中?

How do you add headers to a response with a middleware?

我不知道如何将 headers 添加到中间件的响应中。我同时使用了 ->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 中的相同,但给出

Call to a member function set() on a non-object

其次我尝试

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

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

    return $response;
}

但这给出了

Method [header] does not exist on view.

那么如何从中间件添加 headers?

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

use Illuminate\Http\RedirectResponse;

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

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

我的所有其他中间件似乎 运行 都可以,所以我想它没问题。

这是在 Laravel 5.0 中测试的解决方案,用于将 headers 附加到路由

创建中间件文件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 
});

它也可以,只需添加到中间件:


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

    return $next($request);
}