如果我使用XMLhttprequest调用API,它可以正常工作。但是当我使用angularjs(1.5.6)时,我得到了CORS错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果我使用XMLhttprequest调用API,它可以正常工作。但是当我使用angularjs(1.5.6)时,我得到了CORS错误相关的知识,希望对你有一定的参考价值。

首先,我已将我的localhost端口3000列入白名单以获取跨源请求。我正在构建一个MEAN堆栈应用程序。我正在尝试使用$ http服务来使用API​​。

myApp.controller('minuteController', function($scope,$http) {
$scope.submitButton = function() {
    $http({
        method: 'POST',
        url: 'https://url.example.com/server/oauth/token?grant_type=password&username=username&password=pass1234&origin=local',
        headers: {'Authorization':'Basic asdsadsads=','Content-Type': 'application/json; charset=UTF-8','Accept':'application/json, text/plain,*/*'}
    })
    .then(function successCallback(response) {
        $scope.dataDisplay = response.data;
        console.log(dataDisplay);
    });
}
});

如果我使用相同的细节来制作XMLHttpRequest,它可以正常工作。以下是有效的代码。

 var xmlhttp = new XMLHttpRequest();
var url = "https://url.example.com/server/oauth/token?grant_type=password&username=username&password=pass1234&origin=local";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myObject = JSON.parse(xmlhttp.responseText);
        alert(myObject);
    }
};

xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type","application/json;charset=UTF-8");
xmlhttp.setRequestHeader( "Accept","application/json, text/plain, */*");
xmlhttp.setRequestHeader( "Authorization","Basic asdsadsads=");
xmlhttp.send();

errors I see in my console

Working HTTP request

Not Working HTTP request

答案

终于找到了问题。它通过在data: ''的参数中添加$http.解决了我的问题

另一答案

两个请求之间的区别在于缺少不成功的请求

Content-Type:application / json; charset = UTF-8

并且未指定您打算使用JSON可能与您期望的工作方式不同。

以上是关于如果我使用XMLhttprequest调用API,它可以正常工作。但是当我使用angularjs(1.5.6)时,我得到了CORS错误的主要内容,如果未能解决你的问题,请参考以下文章