【问题标题】:How do you add headers to a response with a middleware?如何使用中间件将标头添加到响应中?
【发布时间】:2015-04-10 07:05:08
【问题描述】:

我不知道如何将标头添加到来自中间件的响应中。我同时使用了->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;
}

但这给了

方法 [header] 在视图中不存在。

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

【问题讨论】:

  • 尝试调试,执行如下代码 echo get_class($response); print_r(get_class_methods($response));你看到了什么?
  • 第二个选项使用$response->header->set('refresh','...') 而不是$response->header('refresh','...')Explanation

标签: laravel laravel-5


【解决方案1】:

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

use Illuminate\Http\RedirectResponse;

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

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

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

【讨论】:

  • 您最好检查一下:instanceof Symfony\Component\HttpFoundation\Response,这样您就可以得到所有类型的回复。
  • 是否应该检查Illuminate\Http\Response
  • 检查 instanceof 对尝试使 CORS 正常工作有很大帮助。谢谢!
【解决方案2】:

这是一个在 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 
});

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 你添加这个是为了请求而不是为了响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2018-08-15
    • 2016-05-15
    • 2019-09-05
    相关资源
    最近更新 更多