thinkphp6设置允许跨域访问

发布于:2021-05-11 21:25:41

80042c98b993ae0b6928b13d1fabf0f5.png



在文件app/middleware.php加入

    \think\middleware\ALLowCrossDomain::class




tp6内置的中间件middleware有点问题,请使用以下中间件


   public function handle($request, \Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,access-control-allow-origin,content-type,xx-devicetype,xx-secretkey,xx-softcode,xx-token');        if (strtoupper($request->method()) == "OPTIONS") {            return Response::create()->send();
        }        return $next($request);
    }


其中    Access-Control-Allow-Headers 里面xx-devicetype,xx-secretkey,xx-softcode,xx-token的参数要增加,不然会包cros错误




https://zhuanlan.zhihu.com/p/105386883


在网站根录下 index.php 下加上

// [ 应用入口文件 ]
// 处理跨域需遇见请求
if(isset($_SERVER['REQUEST_METHOD'])&&$_SERVER['REQUEST_METHOD']=='OPTIONS'){
// 允许的原域名
header('Access-Control-Allow-Origin:*');
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//允许携带证书式访问(携带cookie)
header('Access-Control-Allow-Credentials:true');
exit;
}

然后再你的公共的控制器中 使用tp自带的方法_initialize 或者构造方法 这里使用的是_initialize

// 将要跨域的控制器方法 继承这个公共的控制器 即可

// 初始化方法
public function _initialize(){
parent::_initialize();
header('Access-Control-Allow-Origin:*');
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//允许携带证书式访问(携带cookie)
header('Access-Control-Allow-Credentials:true');
}


阅读 884+

一片空白

父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。