Laravel(Lumen) 导出表格文件响应跨域问题

普通响应跨域,在中间件里是这么设置,设置的是header()方法:

php 复制代码
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Control-Type, Content-Type, token, Accept, x-access-sign, x-access-time, Content-Disposition");
$response->header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

而遇到导出表格文件流,这种文件响应,需要这么设置,设置的是headers属性:

php 复制代码
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Control-Type, Content-Type, token, Accept, x-access-sign, x-access-time, Content-Disposition");
$response->headers->set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

完整示例如下:

php 复制代码
if (!$response instanceof BinaryFileResponse) {
    //普通响应 使使用header()方法来设置CORS头
    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Access-Control-Allow-Credentials', 'true');
    $response->header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Control-Type, Content-Type, token, Accept, x-access-sign, x-access-time, Content-Disposition");
    $response->header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
}else{
    //文件响应 使用headers属性来设置CORS头
    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->headers->set('Access-Control-Allow-Credentials', 'true');
    $response->headers->set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Control-Type, Content-Type, token, Accept, x-access-sign, x-access-time, Content-Disposition");
    $response->headers->set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
}
if ($request->isMethod('OPTIONS')) return $response; //OPTIONS不记录日志
相关推荐
唐青枫2 小时前
php8 命名参数使用教程
php
跨境卫士-小汪5 小时前
关税核爆72小时!跨境矩阵防御战紧急打响
开发语言·php
xujiangyan_6 小时前
php的高速缓存
linux·服务器·php
0白露7 小时前
在Thinkphp中使用JWT 包括JWT是什么,JWT的优势
php
hunzi_11 天前
选择网上购物系统要看几方面?
java·微信小程序·小程序·uni-app·php
唐青枫1 天前
php8 ?-> nullsafe 操作符 使用教程
php
86Eric1 天前
Laravel Trait 实现 统一JSON 响应格式
laravel·trait·api统一响应
Xiaok10181 天前
解决 Hugging Face SentenceTransformer 下载失败的完整指南:ProxyError、SSLError与手动下载方案
开发语言·神经网络·php
Jtti1 天前
PHP在Debian环境上的并发处理能力如何
开发语言·debian·php
viqecel2 天前
网站改版html页面 NGINX 借用伪静态和PHP脚本 实现301重定向跳转
nginx·php·nginx重定向·301重定向·html页面重定向