场景
- lumen5.5环境在定义了一个跨域的中间件,在使用 maatwebsite/excel download方法的时候,报错
:Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()
参考文档
原来的中间件
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,PATCH,DELETE,HEAD')
->header('Access-Control-Allow-Headers', 'x-csrf-token,x-requested-with,content-type');
}
分析
- 一般情况下 n e x t ( next( next(request) 返回的是 Illuminate\Http\Response, 但是使用Excel::download的时候
是\Symfony\Component\HttpFoundation\Response的实例;
解决
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response instanceof Response) {
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,PATCH,DELETE,HEAD')
->header('Access-Control-Allow-Headers', 'x-csrf-token,x-requested-with,content-type');
}
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,PATCH,DELETE,HEAD');
$response->headers->set('Access-Control-Allow-Headers', 'x-csrf-token,x-requested-with,content-type');
return $response;
}