【问题标题】:How to resolve CORS ie same origin policy in angularjs如何在angularjs中解决CORS即同源策略
【发布时间】:2014-08-18 06:24:33
【问题描述】:

我正在使用 angularjs 开发一个移动应用程序,我必须在其中调用 Web 服务。但是,当我使用$http.get 拨打电话时,会出现以下错误。

XMLHttpRequest cannot load http://example.com/First_Step.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access. 

我的功能如下:

$scope.firstStepClick = function() {
    appSvc.selectedItem = "firstStep";
    $rootScope.go('parent/firststep', 'slideLeft');
    delete $http.defaults.headers.common['X-Requested-With'];            
    $http.get("http://example.com/First_Step.json").success(function(data) {
        $scope.firstStepData = data;
    }).error(function() {
        alert("an unexpected error occured");
    });
};

所以,请帮我解决这个 CORS 问题。我正在使用 html5、css3 和 angularjs 来开发这个移动应用程序。

提前致谢

【问题讨论】:

    标签: angularjs angularjs-directive xmlhttprequest cors same-origin-policy


    【解决方案1】:

    阿帕奇:

    http://enable-cors.org/server_apache.html

    nodejs

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    

    阿帕奇吊索

    http://sling.apache.org/apidocs/sling5/org/apache/sling/api/servlets/SlingSafeMethodsServlet.html#doOptions(org.apache.sling.api.SlingHttpServletRequest,org.apache.sling.api.SlingHttpServletResponse) 利用 doOptions 并返回 Allow

    不幸的是,我不是 apache sling 专家,这就是我能够在谷歌上搜索到的程度,检查您的网络选项卡,对您的服务器的第一次调用是“OPTIONS”调用,它返回允许它应该返回的选项 * 或特定的,如“获取”或“发布”,具体取决于需要,然后将进行真正的调用

    【讨论】:

    • 我正在使用 angularjs。我应该为 Apache Sling 做什么?
    【解决方案2】:

    您不必在 Angular 方面做任何事情。

    服务器端负责发送权限标头以启用 CORS

    看看这个:

    http://enable-cors.org/server.html

    【讨论】:

    • 我将如何做到这一点。即,我将如何添加标题以启用 CORS。
    • 嗯,这取决于您在后端使用的技术。我在答案中附加的链接中有很多示例。
    猜你喜欢
    • 2012-08-22
    • 2019-11-16
    • 2016-05-22
    • 2022-07-20
    • 2018-05-25
    • 2016-02-10
    • 2021-04-02
    • 2021-07-14
    • 2014-03-12
    相关资源
    最近更新 更多