【问题标题】:If I call an API using XMLhttprequest, it works fine. But when I use angularjs (1.5.6), I get CORS error如果我使用 XMLhttprequest 调用 API,它可以正常工作。但是当我使用 angularjs (1.5.6) 时,我得到了 CORS 错误
【发布时间】:2018-08-10 20:43:11
【问题描述】:

首先,我已将我的 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();

【问题讨论】:

  • 您是从同一个域发送请求吗?
  • 不,我从本地主机的 3000 端口发送请求。我的 API 服务在另一台服务器上,我已将本地主机端口 3000 列入白名单。就像我说的,如果使用 Javascript XML HTTP 请求调用我没有任何错误。
  • 请注意,不需要在请求上设置“Access-Control-*”标头;那些需要来自服务器的响应。
  • 我只是在尝试。但删除它没有任何区别。
  • 您在 AngularJS 中设置了 withCredentials: true,但不要在 XHR 中这样做。您在 AngularJS 中使用 Content-Type: application/x-www-form-urlencoded,但在 XHR 中使用 Content-Type: application/json。这是将苹果与橙子进行比较。使两者相同。

标签: angularjs http cors xmlhttprequest


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这两个请求的区别在于不成功的请求丢失了

    内容类型:application/json;charset=UTF-8

    如果不指定您打算使用 JSON,可能会与您预期的不同。

    【讨论】:

    • 将我的内容类型值更改为 application/json;charset=UTF-8。我仍然可以看到同样的错误。由于某种原因,我在开发者工具的网络选项卡中的请求标头中看不到内容类型值。
    • @Ashish308 那么它没有被发送。这一定是问题所在。
    • @Ashish308 我看到你找到了解决方案。我会在这里保留我的答案,因为它可能是其他问题的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2019-09-23
    • 2020-09-02
    • 2019-10-08
    • 2017-02-02
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多