php - angular get请求跨域问题?如何通过本地项目跨域获取服务器上的数据?

查看:132
本文介绍了php - angular get请求跨域问题?如何通过本地项目跨域获取服务器上的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我在本地有一个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' }
})

这篇关于php - angular get请求跨域问题?如何通过本地项目跨域获取服务器上的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆