本文主要是介绍laravel报错Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在中间件中使用了
$response->header('Access-Control-Allow-Origin', '*');$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');$response->header('Access-Control-Allow-Credentials', 'true');
所以在使用laravel-excel做excel导出的时候,使用下载,报Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()这个错误。
看了laravel文档,说下载文件用
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend(true);
看来下源码,是用的这个
public function download($export, string $fileName, string $writerType = null, array $headers = []){return response()->download($this->export($export, $fileName, $writerType)->getLocalPath(),$fileName,$headers)->deleteFileAfterSend(true);}
然后网上看了下,说原因是
$response是Illuminate\Http\Response类的一个实例,而Passport实际上使用的是Symfony\Component\HttpFoundation\Response类响应消息
通过查看源码,发现
Illuminate\Http\Response使用了Illuminate\Http\ResponseTrait,而header就是在这里定义的
public function header($key, $values, $replace = true){$this->headers->set($key, $values, $replace);return $this;}
再查看Symfony\Component\HttpFoundation\Response的源码,发现,里面的header是这样的
$this->headers = new ResponseHeaderBag($headers);
查看use Symfony\Component\HttpFoundation\HeaderBag;的源码,这里是处理header的一个类,而Illuminate\Http\ResponseTrait在处理header时也是用的这个,
public function withHeaders($headers){if ($headers instanceof HeaderBag) {$headers = $headers->all();}foreach ($headers as $key => $value) {$this->headers->set($key, $value);}return $this;}
所以从上面的代码看出,我们可以直接使用
$this->headers->set($key, $values, $replace);
那么在中间件中就可以这样用
$response->headers->set('Access-Control-Allow-Origin', '*');$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');$response->headers->set('Access-Control-Expose-Headers', 'Authorization, authenticated');$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');$response->headers->set('Access-Control-Allow-Credentials', 'true');
这篇关于laravel报错Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!