ajax请求适用于$但不是角度

时间:2014-02-12 12:41:14

标签: javascript jquery ajax angularjs http-headers

我有一些jQuery可以获取数据并执行回调:

$(function(){
$.ajax({
    type: 'POST',
    url: 'http://flash-cast-hrd.appspot.com/api/sonar/sync', 
    data: {
        source: 5,
        auth: 'JXEI....DHA2J'
    }, 
    success: displayData
});
});

我正在尝试从我的角度控制器发出相同的请求,我在该范围内有一个方法。

$scope.init = function(){

            $http.post('http://flash-cast-hrd.appspot.com/api/sonar/sync', {
                source: 5,
                auth: 'JXEI....DHA2J'
            })
                .success(function(data){
                    console.log(data);
                })
                .error(function(error){
                    console.log('Error is: ' + error);
                });
        };

然后在视图中调用它:

<div ng-init="init()"></div>

当我加载页面时,我在控制台中收到错误:

OPTIONS http://flash-cast-hrd.appspot.com/api/sonar/sync 405 (Method Not Allowed) angular.js:8021
OPTIONS http://flash-cast-hrd.appspot.com/api/sonar/sync No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. angular.js:8021
XMLHttpRequest cannot load http://flash-cast-hrd.appspot.com/api/sonar/sync. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. :8000/routes:1
Error is:  

如何使角度$ http.post请求有效?

1 个答案:

答案 0 :(得分:0)

问题是因为跨域访问,您可以通过在服务器上设置proxypass来解决,并且您的请求也需要包含Access-Control-Allow-header。