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不记录日志
相关推荐
catchadmin6 小时前
PHP Fiber 优雅协作式多任务
后端·php
DanB246 小时前
Java(网络编程)
java·网络·php
龙泉寺天下行走7 小时前
[PowerShell 入门教程] 第9.5天(间章):PowerShell 常见 Cmdlet 速查手册
开发语言·php
用户607320369458 小时前
PHP header already sent:中文乱码、BOM、空格导致的全套解决方案(图文版)
php
牛奔9 小时前
php 8.2 配置安装php-zbarcode扩展
android·开发语言·php
n***s90910 小时前
ThinkPHP和PHP的区别
开发语言·php
码农运营10 小时前
PayPal 支付效果
php
霸王大陆10 小时前
《零基础学 PHP:从入门到实战》教程-模块四:数组与函数-2
android·开发语言·php
济南壹软网络科技有限公司10 小时前
沉浸式体验革命:壹软科技2025新版盲盒源码前端3D渲染与个性化运营技术解析
前端·科技·uni-app·开源·php·盲盒源码
霸王大陆11 小时前
《零基础学 PHP:从入门到实战》教程-模块四:数组与函数-1
android·开发语言·php