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不记录日志
相关推荐
长安第一美人6 小时前
php出现zend_mm_heap corrupted 或者Segment fault
开发语言·嵌入式硬件·php·zmq·工业应用开发
咕噜签名-铁蛋8 小时前
云服务器远程连接失败?
开发语言·php
JSON_L9 小时前
Fastadmin后台增加切换语言
后端·php·fastadmin
JSON_L10 小时前
Fastadmin API接口实现多语言提示语
后端·php·fastadmin
禁默11 小时前
“零消耗”调用优质模型:AI Ping结合Cline助我快速开发SVG工具,性能与官网无异
开发语言·php
青梅煮久12 小时前
RK3566 Linux实例应用(1)——环境编译与烧录
linux·数据库·php
✎ ﹏梦醒͜ღ҉繁华落℘14 小时前
计算机网络学习(二)---Ping命令
学习·计算机网络·php
码农12138号14 小时前
Bugku - 2023 HackINI Upload0 与 2023 HackINI Upload1 详解
web安全·php·ctf·文件上传漏洞·bugku
my小张15 小时前
最好的子比主题推荐
php
乾元17 小时前
拓扑配置合规自动修正器:AI 发现在网内不一致并建议修复
运维·服务器·开发语言·网络·人工智能·php·运维开发