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不记录日志
相关推荐
小柯博客22 分钟前
从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(十二)
c语言·stm32·单片机·嵌入式硬件·php·嵌入式
冰橙子id10 小时前
centos7编译安装LNMP架构
mysql·nginx·架构·centos·php
永日4567011 小时前
学习日记-day24-6.8
开发语言·学习·php
Clang's Blog12 小时前
一键搭建 WordPress + MySQL + phpMyAdmin 环境(支持 PHP 版本选择 & 自定义配置)
数据库·mysql·php·wordpr
flyair_China16 小时前
【云架构】
开发语言·php
有个傻瓜18 小时前
PHP语言核心技术全景解析
开发语言·kubernetes·php
rorg1 天前
使用 Laravel 中的自定义存根简化工作
php·laravel
斯奕sky_small-BAD1 天前
C++ if语句完全指南:从基础到工程实践
java·开发语言·php
Nick同学1 天前
GatewayWorker 使用总结
后端·php
CRMEB定制开发2 天前
CRMEB 中 PHP 快递查询扩展实现:涵盖一号通、阿里云、腾讯云
阿里云·php·腾讯云·商城系统·商城源码