tp6 解决设置跨域不生效问题

在middleware文件夹下创建AllowCrossDomain.php

<?php
declare (strict_types=1);

namespace app\api\middleware;

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

/**
 * 跨域请求支持
 * 安全起见,只支持了配置中的域名
 */
class AllowCrossDomain
{
    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'     => 'think-lang, server, ba-user-token, batoken, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

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

        $origin = $request->header('origin');
        if ($origin) {
            $info = parse_url($origin);

            // 获取跨域配置
            $corsDomain   = explode(',', Config::get('matter.cors_request_domain'));
            $corsDomain[] = $request->host(true);

            if (in_array("*", $corsDomain) || in_array($origin, $corsDomain) || (isset($info['host']) && in_array($info['host'], $corsDomain))) {
                header("Access-Control-Allow-Origin: " . $origin);
            }
        }

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

在middleware.php中引入

<?php
return [
    \app\api\middleware\AllowCrossDomain::class,
];

如不生效,可不使用上述方法,直接去修改入口文件
在入口文件public/index.php中添加options请求的处理

// 处理 OPTIONS 请求
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    header("'Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token");
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
    exit; // 直接退出,不走后序流程
}
### ThinkPHP6 图片解决方案 在ThinkPHP6中处理图片访问问题时,可以采取多种策略。以下是一些常见的方法及其详细说明: #### 1. **使用中间件解决** 创建一个新的中间件文件 `app/http/middleware/Cors.php` 并添加必要的头信息以支持请求[^4]。 ```php <?php namespace app\http\middleware; class Cors { public function handle($request, \Closure $next) { header('Access-Control-Allow-Origin: *'); // 允许所有名访问 header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // 支持的HTTP动词 header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); // 允许自定义头部字段 if ($request->isOptions()) { // 如果是预检请求直接返回 return response('', 204); } return $next($request); } } ``` 接着,在 `app/middleware.php` 中注册该中间件: ```php return [ \app\http\middleware\Cors::class, ]; ``` 此方法适用于整个应用都需要支持的情况。 #### 2. **修改入口文件 (public/index.php)** 可以直接在项目的入口脚本中加入的支持逻辑[^5]: ```php header("Access-Control-Allow-Origin: *"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header("Access-Control-Allow-Headers: *"); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); exit; } ``` 这种方法简单有效,但对于大型项目而言不够灵活,因为它影响到了所有的请求。 #### 3. **Nginx/Apache 配置层面解决问题** ##### 对于 Nginx 用户: 可以通过调整 Nginx 的配置来实现更高效的控制[^2]。例如: ```nginx server { listen 80; server_name yourdomain.com; location /images/ { add_header Access-Control-Allow-Origin *; try_files $uri =404; } # 处理预检请求 if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'Origin, X-Requested-With, Content-Type, Accept, Authorization'; return 204; } } ``` 重启 Nginx 后生效。 ##### 对于 Apache 用户: 同样可以在 .htaccess 文件中设置类似的规则[^3]: ```apache <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" <LimitExcept OPTIONS> Require all granted </LimitExcept> SetEnvIf Origin "^https?://" allowed_cors=true Header always set Access-Control-Allow-Credentials "true" env=allowed_cors Header always merge Vary Origin </IfModule> ``` 以上两种方式都能够在 Web Server 层面很好地应对挑战,尤其当只涉及静态资源(如图片)的时候显得尤为合适。 --- ### 结论 综合考虑效率与维护成本等因素,建议优先尝试通过Web服务器(Nginx或Apache)配置的方式来处理图片这类静态资源的问题。而对于动态数据交互,则更适合运用框架内置的功能比如中间件来进行全局性的设定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值