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不记录日志
相关推荐
4311媒体网8 小时前
帝国cms调用文章内容 二开基本操作
java·开发语言·php
Evan芙11 小时前
nginx+php部署walle,发布php站点
运维·nginx·php
catchadmin11 小时前
PHP 8.6 即将支持部分函数应用
php
未来之窗软件服务15 小时前
幽冥大陆(四十九)PHP打造Java的Jar实践——东方仙盟筑基期
java·php·jar·仙盟创梦ide·东方仙盟·东方仙盟sdk·东方仙盟一体化
BingoGo16 小时前
Laravel + Vue3 前后端分离开源后台管理框架 CatchAdmin v5.0 Beta 发布
后端·php
行思理17 小时前
Linux多PHP如何切换系统默认PHP版本
linux·运维·php
pandarking18 小时前
[CTF]攻防世界:easy_laravel 学习
java·学习·web安全·laravel·ctf
Web极客码20 小时前
如何通过GUI或命令行更改Ubuntu 20.04的DNS设置
linux·ubuntu·php
毕设源码-朱学姐20 小时前
【开题答辩全过程】以 基于PHP的高校心理测评系统的设计与实现为例,包含答辩的问题和答案
开发语言·php
JaguarJack20 小时前
PHP 8.6 新增 clamp() 函数
后端·php