php - angular get请求跨域问题?如何通过本地项目跨域获取服务器上的数据?
迷茫
迷茫 2017-04-10 17:34:00
[PHP讨论组]

我在本地有一个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有内容
?>
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(3)
ringa_lee
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 的错误

阿神

headers : {

              'Content-Type' : 'application/x-www-form-urlencoded' //跨域请求头
        },
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号