laravel-excel 导出跨域报错

这里就省略laravel-excel的流程了
如果启动了跨域的话;导出功能会报错:Call to undefined method Symfony\Component\HttpFoundation\Response::header()
解决办法如下:
在中间件根据请求类去用不同的header 方法

const ILLUMINATE_RESPONSE = 'Illuminate\Http\Response';
const SYMFONY_RESPONSE = 'Symfony\Component\HttpFoundation\Response';

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);
    $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '*';
    $headers = [
        'Access-Control-Allow-Origin' => $origin,
        'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers, X-CSRF-TOKEN',
        'Access-Control-Expose-Headers' => 'Authorization, authenticated',
        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTION',
        'Access-Control-Allow-Credentials' => 'true'
    ];

    $IlluminateResponse = self::ILLUMINATE_RESPONSE;
    $SymfonyResponse = self::SYMFONY_RESPONSE;

    switch ($response) {
        // 普通的http请求
        case ($response instanceof $IlluminateResponse) :
            foreach ($headers as $key => $value) {
                $response->header($key, $value);
            }
            break;
        // laravel-excel
        case ($response instanceof $SymfonyResponse):
            foreach ($headers as $key => $value) {
                $response->headers->set($key, $value);
            }
            break;
    }

    return $response;
}

 

 

你可能感兴趣的:(网站)