ThinkPhp配置中间件解决跨域问题

 

在ThinkPHP框架中,配置跨域可以通过中间件或者行为来实现。以下是通过中间件配置跨域的方法:

  1. 在应用目录(application)下创建一个中间件目录(如果还没有的话),例如 application/middleware

  2. 在该目录下创建一个跨域处理的中间件文件,例如 CrossDomain.php

  1. 注册中间件。在应用配置文件中注册刚创建的中间件。

    // application/middleware/CrossDomain.php
    
    namespace app\middleware;
    
    class CrossDomain
    
    {
    
    public function handle($request, \Closure $next)
    
    {
    
    $response = $next($request);
    
    // 设置跨域
    
    $response->header([
    
    'Access-Control-Allow-Origin' => '*', // 允许任何源
    
    'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
    
    'Access-Control-Allow-Headers' => 'Content-Type, Accept, Authorization, X-Requested-With, Origin, X-CSRF-Token',
    
    ]);
    
    // 如果请求类型为OPTIONS,直接返回响应,结束请求
    
    if (strtoupper($request->method()) == "OPTIONS") {
    
    return $response;
    
    }
    
    // 继续处理其他请求
    
    return $response;
    
    }
    
    }
ThinkPHP 5.6 中解决(CORS)问题,可以通过在控制器或全局中间件中设置响应头来实现。以下是一个常见的解决方案: ### 方法一:在控制器中设置头 ```php namespace app\index\controller; use think\Controller; use think\Response; class Index extends Controller { public function index() { // 设置允许名(* 表示允许所有名) header('Access-Control-Allow-Origin: *'); // 允许请求的方法 header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE'); // 允许的请求头信息 header('Access-Control-Allow-Headers: Content-Type,Authorization'); // 如果是预检请求(OPTIONS),直接返回成功 if (request()->isOptions()) { return response('', 200); } // 正常返回数据 return json(['code' => 1, 'msg' => 'success']); } } ``` --- ### 方法二:使用中间件全局处理(推荐) 创建一个中间件统一处理请求: 1. 创建中间件: ```bash php think make:middleware Cors ``` 2. 编辑中间件文件 `app/http/middleware/Cors.php`: ```php namespace app\http\middleware; use think\Response; class Cors { public function handle($request, \Closure $next) { $response = $next($request); // 如果是响应对象,添加头 if ($response instanceof Response) { $response->header([ 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers' => 'Content-Type,Authorization', ]); } return $response; } } ``` 3. 在 `app/http/controller` 中的控制器或全局应用中注册中间件。 --- ### 方法三:通过配置文件定义全局(需自定义) 在 `config/app.php` 中添加配置项,或在入口文件 `public/index.php` 中添加全局头信息: ```php // public/index.php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type,Authorization'); if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit; } ``` --- ### 总结 以上三种方式都可以解决 ThinkPHP 5.6 的问题,推荐使用中间件方式统一处理,便于维护和扩展。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值