解决TP5.1 CORS跨域问题

第一种方法:在index.php入口页面

// 响应头设置 我们就是通过设置header来跨域的 这就主要代码了 定义行为只是为了前台每次请求都能走这段代码
if(!empty($_SERVER)&&($_SERVER['REQUEST_METHOD'] == 'OPTIONS')){
    //tp5.1代码有 header("Access-Control-Allow-Origin: *") 这里需要屏蔽,否则报错
   // header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Headers:token,Origin,X-Requested-With,Content-Type,content-type,Accept,Authorized-Token,Authori-zation,Authorization,authorized-token');
    header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
    //Access-Control-Allow-Credentials为truede 时候,Access-Control-Allow-Origin不能设置为*
    //    header('Access-Control-Allow-Credentials:false');
    exit;
}

 

第二种解决方式

1.在 application->tags.php 文件中添加如下代码

return [
    // 应用初始化
    'app_init'     => [],
    // 应用开始
    'app_begin'    => [
        'app\\common\\behavior\\CORS'
    ],
    // 模块初始化
    'module_init'  => [],
    // 操作开始执行
    'action_begin' => [],
    // 视图内容过滤
    'view_filter'  => [],
    // 日志写入
    'log_write'    => [],
    // 应用结束
    'app_end'      => [
        'app\\common\\behavior\\CORS'
    ],
];

2.application->common->behavior->CORS.php 添加如下代码

namespace app\common\behavior;
/**
 * CORS跨域
 */
class CORS
{
    public function run()
    {// 响应头设置 我们就是通过设置header来跨域的 这就主要代码了 定义行为只是为了前台每次请求都能走这段代码
        $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
//        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:token,Origin,X-Requested-With,Content-Type,content-type,Accept,Authorized-Token,Authori-zation,Authorization,authorized-token,If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since');
        header('Access-Control-Allow-Credentials:false');
        if (request()->isOptions()) {
            exit();
        }
    }
}