我在本地有一个angular的项目文件。
我在run运行块里面写了个$http:
app.run(function ($rootScope, $http) {
$http({
method: 'GET',
url: 'http://xxx/data/count.php',
params: { 'mode': 'nor' }
}).success(function (response) {
console.log(response)
})
});
然后一开始我在网上查询了一下失败的原因,在服务器的php接口文件上加上了header
header("Access-Control-Allow-Origin: *");
可是错误依然:
XMLHttpRequest cannot load http://xxx/data/count.php?mode=nor. Request header field Pragma is not allowed by Access-Control-Allow-Headers in preflight response.
请问如何才能让本地的angular代码能够获取到远端数据?
附上php接口文件代码:
<?php
header('Access-Control-Allow-Origin:*');
$list=num_it($_GET["site"]);
$res=get_son_where($list);
$res=array_iconv("gb2312","utf-8//IGNORE",$res);
$result=["collist"=>$res];
echo json_encode($result);
//$result有内容
?>
header('Access-Control-Allow-Origin: http://xxx');
这里不要写
*
,最好写完整的
http://xxx
,因为
Access-Control-Allow-Headers
在跨域的涉及的数据交换时必须要严格指定来源。
然后浏览器端需要交互cookie等的话,还需要js中加
withCredentials: true
$http({
method: 'GET',
url: 'http://xxx/data/count.php',
withCredentials: true,
params: { 'mode': 'nor' }
})
利用 Interceptors 来统一处理 HTTP 的错误