记住用户名密码
我们通常在进行接口调用时,会出现报错:
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.
遇到这个错误,其实是因为跨域了,那么什么是跨域访问呢?
我们通常在进行接口调用时,会出现报错:
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.qqqqq.cn', ]; $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');
目前有 0 条留言 其中:访客:0 条, 博主:0 条