我们通常在进行接口调用时,会出现报错:Access to XMLHttpRequest at ‘http:/xxxxxxxxxx from origin ‘http://xxxxxxxxxx’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
这种错误就是表示出现了跨域。那么什么是跨域访问呢?
就是不同域名,端口之间相互调用数据,会出现验证失败的情况。
那么应该怎么解决跨域报错请求呢?
其实很简单,在php中设置头就行。
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE"); header('Access-Control-Allow-Headers:Origin,Content-Type,Accept,token,X-Requested-With,device');
借鉴其他答案,多域名实现跨域:
// 可跨域域名列表 $domains = [ 'http://localhost:8080', 'http://test.52lc.top', ]; $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; if (in_array($origin, $domains)) { header('Access-Control-Allow-Origin:' . $origin); } // 允许的请求头信息 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); //在请求头里加上需要允许的 header("Access-Control-Allow-Headers: Origin, 名称); // 允许的请求类型 header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); // 允许携带证书式访问(携带cookie) header('Access-Control-Allow-Credentials:true');
发布评论