使用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; }