当前位置: 首页 > article >正文

ThinkPhp项目解决静态资源请求的跨域问题的解决思路

背景:我在前端使用vue语言开发的,请求的后端是用ThinkPhp项目开发的。我vue项目里的请求php接口,自带header参数的跨域问题通过网上查询到的server端配置方法已经解决了。我使用的

是中间件的配置方法:

<?php

//admin 项目 配置中间件
use app\admin\middleware\MyCrossDomain;

return [
     MyCrossDomain::class
]; 

 MyCrossDomain.php

<?php
namespace app\admin\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

/**
 * 跨域请求支持
 */
class MyCrossDomain
{
    protected $cookieDomain;

    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Code,Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param array   $header
     * @return Response
     */
    public function handle(Request $request, Closure $next, array $header = []): Response
    {
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->cookieDomain || str_contains($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }

        return $next($request)->header($header);
    }
}

这样之后前端项目通过axios接口请求不再报跨域的错了,这一阶段的问题已经解决。

现在有一个新的问题,我在Thinkphp项目里有一个静态的json文件,H5要通过<link>的方式要请求它。类似这样的:

   document.write("<link rel='manifest' href='https://landpage-server.appboost.co/admin/file/xxxxx/xxxx.json');

虽然我的ThinkPhp项目已经配置了跨域的,但是对于请求这个静态文件还是报跨域的问题。折腾了好久,各种配置还是不行。最后我尝试了一种办法,就是专门写一个Controller来响应静态文件的返回。代码如下:

StaticResourceController.php

<?php

namespace app\admin\controller;

use app\admin\model\LogEvents;
use app\admin\model\PixelInfo;
use app\admin\model\ReleasePlatform;
use app\admin\model\ReleaseUrl;
use app\admin\model\User;
use app\admin\model\Wallet;
use app\admin\model\WalletLog;
use app\BaseController;
use app\Response;
use Ramsey\Uuid\Uuid;
use think\facade\Console;
use think\facade\Db;

class StaticResourceController extends MBaseController{
     public function getManifestJson(){

            $company_code = input("get.code");
            $promote_code = input("get.id");


            // echo root_path();
      

            $root =  root_path();
            $dir = $root ."public/page/";

            // echo $dir;

            $content = $this->openFile($dir,$company_code,$promote_code);

            $obj = json_decode($content);
            return json($obj, 200);
     }


     public function openFile($dir, $company_code,$promote_code){
        $filePath = $dir.$company_code."/".$promote_code.".json"; // 文件路径
        $mode = 'r'; // 打开模式
        
        $fileHandle = fopen($filePath, $mode);

        $content = fread($fileHandle, filesize($filePath));
        
        if ($fileHandle === false) {
            die('无法打开文件');
        }
        
        fclose($fileHandle);

        return $content;
    }
}

H5端请求是这样的:

   document.write("<link rel='manifest' href='https://landpage-server.appboost.co/admin/staticResource/getManifestJson?

code="+$company_code+"&id="+$promote_code+"'>");

谢天谢地,终于不报跨域的问题了,成功拿到了json静态文件。


http://www.kler.cn/a/511605.html

相关文章:

  • C# 动态创建Label和ComboBox控件并修改Text
  • 大数据时代的璀璨明珠:机器学习引领的智能应用革新与深度融合探索
  • 【2024年华为OD机试】 (B卷,200分)- 跳格子游戏(Java JS PythonC/C++)
  • 第三部分:Linux中的yum
  • 有线通信方式(I2C、UART)
  • 设计模式:构建高效且可维护的软件系统的基石
  • 车载测试和相关面试
  • 类和对象——类的对象占用内存的大小计算
  • 【C++】内存管理与分配
  • Leetcode::3427.变长子数组求和
  • vue+高德API搭建前端Echarts图表页面
  • JavaScript笔记基础篇04——对象
  • win内核内部直接irp读取文件写入文件
  • RabbitMQ 进阶
  • Linux内存管理(Linux内存架构,malloc,slab的实现)
  • 排序算法(C语言版)
  • Vue3数据响应式原理
  • PHP变量
  • TiDB 和 MySQL 的关系:这两者到底有什么不同和联系?
  • Linux(NFS服务)