Setting response headers with middleware in Lumen

北战南征 提交于 2019-12-25 03:33:26

问题


I'm trying to set a header (X-Powered-By) using an AfterMiddleware in the Lumen micro-framework. Unfortunately, the header isn't being set. It is assumed that the middleware (shown below) isn't even being handled.

AfterMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;

class AfterMiddleware {

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

        $response->header('X-Powered-By', env('APP_NAME') . '/' . env('APP_VER'));

        return $response;
    }
}

bootstrap/app.php middleware setter

$app->middleware([
    'App\Http\Middleware\AfterMiddleware'
]);

Am I missing something here?


回答1:


Figured it out: the middleware won't be handled for Exceptions (404, in my case). My temporary solution is to simply add the header to the response directly in the exception handler.

if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
    return response(view('not-found'), 404)->header('X-Powered-By', env('APP_NAME')."/".env('APP_VER'));
}

Unfortunately, the header is being duplicated, even though $replace defaults to true. Will open a new question for that.



来源:https://stackoverflow.com/questions/30402806/setting-response-headers-with-middleware-in-lumen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!