加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用Angular JS调用restful API时的跨域问题

发布时间:2020-12-17 10:20:06 所属栏目:安全 来源:网络整理
导读:我正在尝试访问一个安静的API.这给出了错误.如何克服这个跨域问题? 错误是’Access-Control-Allow-Origin’标头出现在请求的资源上 function Hello($scope,$http) {$http.get('http://api.worldweatheronline.com/free/v1/weather.ashx?q=Londonformat=json
我正在尝试访问一个安静的API.这给出了错误.如何克服这个跨域问题?

错误是’Access-Control-Allow-Origin’标头出现在请求的资源上

function Hello($scope,$http) {

$http.get('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev').
    success(function(data) {
        alert("Success");
    }).
    error(function(data){
       alert("Error");
    });
}

这是我的小提琴http://jsfiddle.net/U3pVM/2654/

更好的方法( fiddle example)是使用 $http.jsonp.
var url = 'http://api.worldweatheronline.com/free/v1/weather.ashx';
return $http.jsonp(url,{
    params: {
        callback: 'JSON_CALLBACK',q: 'London',format:'json',num_of_days: 5,key: 'atf6ya6bbz3v5u5q8um82pev'
    }
});

请注意我添加的JSON_CALLBACK查询字符串参数.在幕后角度使用它来为你设置回调.没有它它会破裂.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读