【发布时间】: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