Php Laravel请求通过错误的中间件路由
我想将http响应头添加到我应用程序上的所有响应中。我刚刚创建了一个新的中间件,以便如下所示:Php Laravel请求通过错误的中间件路由,php,laravel,php-7.2,Php,Laravel,Php 7.2,我想将http响应头添加到我应用程序上的所有响应中。我刚刚创建了一个新的中间件,以便如下所示: namespace Ibbr\Http\Middleware; use Closure; class XFrameOptionsHeader { public function handle($request, Closure $next) { $response = $next($request); $response->header('X
namespace Ibbr\Http\Middleware;
use Closure;
class XFrameOptionsHeader
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('X-Frame-Options', 'deny');
return $response;
}
}
然后,将它添加到我的Kernel.php
protected $middlewareGroups = [
'web' => [
\Ibbr\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Ibbr\Http\Middleware\VerifyCsrfToken::class,
\Ibbr\Http\Middleware\XFrameOptionsHeader::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \Ibbr\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verificaCookieArquivo' => \Ibbr\Http\Middleware\VerificaCookieArquivo::class,
'xFrameOptionsHeader' => \Ibbr\Http\Middleware\XFrameOptionsHeader::class,
]
在路线定义中,我有:
Route::group(['middleware'=>['verificaCookieArquivo']], function(){
Route::get('/storage/{filename}', 'PagesController@getArquivo');
});
Route::group(['middleware'=>['web','xFrameOptionsHeader']], function(){
Route::get('/', 'PagesController@getIndex');
// more routes...
});
每当我调用第二组中的任何路由时,['web','xframeoptionheader']
它都会正常工作并返回新的http头。但是,当我调用路由/storage/{filename}
时,它会失败并出现错误
调用未定义的方法
Symfony\Component\HttpFoundation\BinaryFileResponse::header()
因此,首先,在考虑此上下文中是否存在header函数之前,我发现更奇怪的是,在这种情况下调用此中间件,我认为它将只调用
verificaCookieArquivo
mid。为什么会发生这种情况,以及如何解决?顺便说一句,我使用的是laravel-5.7,但它不是标签。只需从web
中间件组中删除\Ibbr\Http\Middleware\xframeoptionheader::class,
web
中间件组自动应用于routes/web.php
。因此,这就是运行中间件的原因:
Route::group(['middleware'=>['verificaCookieArquivo']], function(){
Route::get('/storage/{filename}', 'PagesController@getArquivo');
});
此外,您也不需要在下一个路线组中指定web
:
Route::group(['middleware'=>['web','xFrameOptionsHeader']], function(){
// ^-- Remove this
Route::get('/', 'PagesController@getIndex');
// more routes...
});
参考资料:我可以看看整个
middlewareGroups
?在许多情况下,添加web
中间件的问题已经解决。'middleware'=>['web','verificaCookieArquivo']
@Wreigh我已经将其添加到了OP中。@Saman我已经尝试过,但也没有成功