TP6自带的跨域中间件无法使用的个人解决方法
使用TP6,因为需要跨域上传图片,一直不成功,网上搜了好久,方法都没解决跨域上传文件
比如下面的方式没成功
$this->app = $app; $this->request = $this->app->request; // 支持跨域请求的host数组['a.cn', 'b.cn'] $corsHost = config('mysite.cors_host'); if (!empty($corsHost) && is_array($corsHost) && in_array($this->request->host(), $corsHost)) { header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With"); header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS"); header("access-control-allow-credentials: true"); header('Access-Control-Allow-Origin: ' . $this->request->domain()); } if($this->request->isOptions()) { exit; }
发现 问题出在 $this->request->domain() ,返回的结果一直是请求地址,
比如 a.cn跨域访问b.cn的资源, $this->request->domain() 值为 b.cn ,但是Access-Control-Allow-Origin需要返回的是a.cn
最后只能这样了
$this->app = $app; $this->request = $this->app->request; // 支持跨域请求的host数组['a.cn', 'b.cn'] $corsHost = config('mysite.cors_host'); if (!empty($corsHost) && is_array($corsHost) && isset($_SERVER['HTTP_ORIGIN']) && in_array(parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST), $corsHost)) { header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With"); header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS"); header("access-control-allow-credentials: true"); // header('Access-Control-Allow-Origin: ' . $this->request->domain()); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } if($this->request->isOptions()) { exit; }