后端跨域处理之Thinkphp5

2020.02.04
评论

thinkphp5处理

1.在项目application下创建目录极其文件:common/behavior/CronRun.php

2.在CronRun.php中写入

<?php
namespace app\common\behavior;
 
use think\Exception;
use think\Response;
 
class CronRun
{
    public function run(&$dispatch){
        $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
        $headers = [
            "Access-Control-Allow-Origin" => $host_name,
            "Access-Control-Allow-Credentials" => 'true',
            "Access-Control-Allow-Headers" => "X-Token,x-uid,x-token-check,x-requested-with,content-type,Host"
        ];
        if($dispatch instanceof Response) {
            $dispatch->header($headers);
        } else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            $dispatch['type'] = 'response';
            $response = new Response('', 200, $headers);
            $dispatch['response'] = $response;
        }
    }
}

3.在项目application下找到tags.php文件,打开并修改

// 应用开始
'app_begin'    => [
   'app\\common\\behavior\\CronRun'
],
// 应用结束
'app_end'      => [
    'app\\common\\behavior\\CronRun'
],