TP5 跨域请求处理

TP5 跨域

关于TP5 跨域 , 官方的添加钩子的方法我是没有用明白 , 用其他方式实现了一下
在extend/service下面编辑一个工具类: ToolsService 写下一个 corsOptionsHandler 方法在你的BaseController中引入执行就OK了

<?php
// 系统工具服务
namespace service;
class ToolsService {
    public static function corsOptionsHandler() {
            if (request()->isOptions()) {
                header('Access-Control-Allow-Origin:*');
                header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
                header('Access-Control-Allow-Credentials:true');
                header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
                header('Access-Control-Max-Age:1728000');
                header('Content-Type:text/plain charset=UTF-8');
                header('Content-Length: 0', true);
                header('status: 204');
                header('HTTP/1.0 204 No Content');
            }else{
                header('Access-Control-Allow-Origin:*');
                header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
                header('Access-Control-Allow-Credentials:true');
                header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
            }
        }
}

BaseController

<?php
namespace app\common\controller;
use think\Controller;
use service\ToolsService;
class BaseController extends Controller
{
    /**
    * 基础接口
    * @param Request|null $request
    */
    public function __construct(Request $request = null) {
            // CORS 跨域 Options 检测响应
            ToolsService::corsOptionsHandler();
    }
}

相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页