TP6自带的跨域中间件无法使用的个人解决方法
使用TP6,因为需要跨域上传图片,一直不成功,网上搜了好久,方法都没解决跨域上传文件
比如下面的方式没成功
$this->app = $app; $this->request = $this->app->request; // 支持跨域请求的host数组['a.cn', 'b.cn'] $corsHost = config('mysite.cors_host'); if (!empty($corsHost) && is_array($corsHost) && in_array($this->request->host(), $corsHost)) { header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With"); header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS"); header("access-control-allow-credentials: true"); header('Access-Control-Allow-Origin: ' . $this->request->domain()); } if($this->request->isOptions()) { exit; }
发现 问题出在 $this->request->domain() ,返回的结果一直是请求地址,
比如 a.cn跨域访问b.cn的资源, $this->request->domain() 值为 b.cn ,但是Access-Control-Allow-Origin需要返回的是a.cn
最后只能这样了
$this->app = $app; $this->request = $this->app->request; // 支持跨域请求的host数组['a.cn', 'b.cn'] $corsHost = config('mysite.cors_host'); if (!empty($corsHost) && is_array($corsHost) && isset($_SERVER['HTTP_ORIGIN']) && in_array(parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST), $corsHost)) { header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With"); header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS"); header("access-control-allow-credentials: true"); // header('Access-Control-Allow-Origin: ' . $this->request->domain()); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } if($this->request->isOptions()) { exit; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 我与微信审核的“相爱相杀”看个人小程序副业
· DeepSeek “源神”启动!「GitHub 热点速览」
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库