【问题标题】:How to handle CORS requests in AngularJS如何在 AngularJS 中处理 CORS 请求
【发布时间】:2017-11-01 05:06:02
【问题描述】:

我在调用 Web 服务时遇到 AngularJS 中的 CORS 请求问题,但同样的服务可以使用 jQuery 进行调用。

注意:我们从服务器端接收到标题 "Access-Control-Allow-Origin:*" 并且这些服务在 jQuery 应用程序中运行良好。

我在这里发布我的 AngularJS 代码以及 jQuery 代码。

AngularJS:

$http({
        method: 'POST',
        url:  $rootScope.host + "UserLogin",
        //headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
            "uname": $scope.uname,
            "password": $scope.password
        },
    }).then(function (success) {
                $scope.loginDetails = success;
                console.log($scope.loginDetails);
    }),function (error){
            console.log(error);
});

如果我通过 headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 之类的标头可以 ping 服务但我的请求不是 JSON 格式。

如果我把标题改成'Content-Type': 'application/json',得到

XMLHttpRequest 无法加载https://XXXX.XXXX.in/XXXXAPI/UserLogin。

对预检请求的响应未通过访问控制检查:

请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://170.11.0.61' 因此不允许访问。

我不知道这个错误的原因是什么。

$.ajax({
    url: BASE_URL + "UserLogin",
    type: "POST",
    xhrFields: {withCredentials: true},
    data: {
        "uname": uname,
        "password": password
    },
    cache: false,
    success: function (result, textStatus, request) {
        console.log(result);
    },
    error: function (e) {
        console.log("Error in login service call:"+JSON.stringify(e));
    }
});

这个 jQuery 以 json 格式发送我的请求。

【问题讨论】:

    标签: angularjs web-services cors


    【解决方案1】:

    尝试传递类似的标题

    headers: { 'Content-Type': 'application/json' }
    

    【讨论】:

    • 如果我更改了标题,我的服务调用不会 ping 服务器并显示“XMLHttpRequest 无法加载 XXXX.XXXX.in/XXXXXAPI/UserLogin。对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow -Origin' 标头存在于请求的资源上。因此不允许访问 Origin '172.16.0.61'。"
    猜你喜欢
    • 2014-10-31
    • 2016-10-30
    • 2018-10-07
    • 2015-03-15
    • 2020-06-30
    • 2018-07-24
    • 2013-11-25
    • 2016-02-17
    • 2020-06-30
    相关资源
    最近更新 更多