对Web Service的AngularJS $ http请求需要CORS

时间:2015-12-16 08:52:47

标签: angularjs web-services http-request

我正在编写一个需要访问WebService的服务(我无法控制) - 我想在我的应用程序中使用的API。我在浏览器中访问了相关网址并且登录成功,我可以看到我的访问令牌,但是当我尝试使用$http访问同一页面时,我在IE中的开发者控制台中收到错误。

angular.module("app").factory("MyService", function($http){
    var serviceUrl = "http://some-web-page/service.asmx/";

    var logOn = function(username, password){
        var getUrl = serviceUrl + "logOn?username="+username+"&password="+password;
        $http.get(getUrl).then(
                function successCallback(response){
                    console.log("Success");
                    console.log(response);
                }, function errorCallback(response){
                    console.log("Error");
                    console.log(response);
                }
        );
    };

    return {
        logOn: logOn
    };
}).config(function($httpProvider){
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

在控制台中我得到了

HTML1300: Navigation occurred.
File: home
HTML1503: Unexpected start tag.
File: home, Line: 5, Column: 1
SEC7118: XMLHttpRequest for http://some-web-page/service.asmx/logOn?username=username&password=password required Cross Origin Resource Sharing (CORS).
File: home
SEC7115: :visited and :link styles can only differ by colour. Some styles were not applied to :visited.
File: home

SEC7120: Origin http://localhost not found in Access-Control-Allow-Origin header.
File: home
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.

2 个答案:

答案 0 :(得分:1)

您不能从客户端向远程服务器发出查询(无论您使用哪个框架,其下面都是基于XMLHttpRequest构建的),除非它们在其侧面启用并实现CORS(服务器托管在{{ 3}})。您可以向服务器以及从服务器向远程服务器发出请求,但这并不总是理想的解决方案。

答案 1 :(得分:0)