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不记录日志
相关推荐
liuxin_07253 小时前
vscode cursor
php
桌面运维家3 小时前
KVM虚拟机:Neutron网络故障诊断与修复实战
服务器·网络·php
hzb666664 小时前
xd_day32-day40
java·javascript·学习·安全·web安全·tomcat·php
思茂信息5 小时前
CST软件加载 Pin 二极管的可重构电桥仿真研究
服务器·开发语言·人工智能·php·cst·电磁仿真·电磁辐射
徒 花6 小时前
HCIA知识整理2
开发语言·php
大黄说说7 小时前
PHP 数组 vs SPL 数据结构:队列与栈场景下的性能对决
开发语言·数据结构·php
一只会跑会跳会发疯的猴子7 小时前
php操作mysql数据库增删改查
数据库·mysql·php
luanma1509808 小时前
PHP vs Lua:脚本语言核心差异解析
开发语言·php·lua
新缸中之脑8 小时前
/last30days 趋势研究技能
开发语言·数据库·php
Joy T8 小时前
【Web3】智能合约多环境部署架构:Mock机制与依赖注入实战
开发语言·架构·web3·区块链·php·智能合约·mock合约