呼吁采用了棱角分明的JS一个宁静的API跨域问题 [英] Cross domain issue in calling a restful API using Angular JS

查看:77
本文介绍了呼吁采用了棱角分明的JS一个宁静的API跨域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图访​​问一个宁静的API。这使错误。如何克服这种跨域问题?

I'm trying to access a restful API. This gives error. How to overcome this Cross domain issue?

错误是访问控制允许来源标头的请求的资源present

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/

推荐答案

一个更好的办法来做到这一点(小提琴例如)是使用 $ http.jsonp

A better way to do this (fiddle example) is to use $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 查询字符串参数。幕后角度使用该设置的回调为您服务。没有它,它会打破。

Notice the JSON_CALLBACK query string parameter I added. Behind the scenes angular uses that to setup its callbacks for you. Without it it will break.

这篇关于呼吁采用了棱角分明的JS一个宁静的API跨域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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