javascript - ajax 请求适用于 $ 但不适用于 Angular

标签 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
});
});

我正在尝试从我的 Angular Controller 发出相同的请求,其中我在范围上有一个方法。

$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);
                });
        };

然后在 View 中调用它:

<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:  

如何使 Angular $http.post 请求起作用?

最佳答案

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

关于javascript - ajax 请求适用于 $ 但不适用于 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728260/

相关文章:

JavaScript自动将切片图片添加到div

javascript - 使用 setInterval 函数和 React 卡住 Chrome

javascript - 我应该使用 iframe 加载外部 html 吗?

Javascript、Jquery 在本地主机中工作正常,但在部署的站点中却不行?

javascript - 我可以使用哪些 jQuery/JavaScript 速记或实践来使此代码更简约?

javascript - jquery 中的数据表不实时刷新数据

javascript - 仅使用一个按钮 OnClick AJAX 更新多个字段

javascript - 如何通过 JavaScript 方法关闭 primefaces 面板?

javascript - 选择复选框时显示数据

javascript - 从 javascript 加载和缓存脚本