如问题所述,我使用 xmlhttprequest 类和 jquery ajax 成功地从服务器加载数据。但我无法在 Angular ajax 中执行此操作,它表示没有“Access-Control-Allow-Origin”。
注意:另外,当 jquery 版本降级到低于 3 时,它也会像 angular ajax 一样显示 No 'Access-Control-Allow-Origin'。它们有任何联系吗???
这里是 jquery ajax 代码,它可以工作,但在将版本从 3 降级到低于 3 时同样不起作用:
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){ $.ajax({
url:'http://...',
data:"{\"city\":\"Kolkata\"}",
method:'post',
headers:{'Content-Type': 'application/json','accept': 'application/json'},
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
});
下一个版本是正常的 xmlhttprequest 版本,它也可以工作
$( window ).load(function() {
var http = new XMLHttpRequest();
var url = "...";
var params = "{\"city\":\"Kolkata\"}";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("accept", "application/json");
//Send the proper header information along with the request
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
});
但是angular1 ajax代码不工作。angular版本是最新的。
$http({
method: 'POST',
url: '...',
headers: {'Content-Type': 'application/x-www-form-urlencoded,application/json',
'Accept':'application/json'},
data: {'city':'Kolkata'}
}).then(function successCallback(response){
console.log(response);
//return response;
},function errorCallback(response){
//return response;
console.log(response);
});
感谢您的宝贵时间。
最佳答案
答案可能在您的 chrome devtools 网络选项卡中。查看每个请求的请求和响应 header ,特别是任何 CORS header 和 Origin
header ,寻找 jQuery 和 Angular 版本之间的差异。
此外,查看是否有任何 OPTIONS
方法类型的 http 请求,如果有,则 Angular 调用可能正在尝试发送更多 header 或发送凭据,这会将其标记为 CORS .
如果您不能减少 Angular 请求以不触发 CORS,您应该能够修改服务器代码以设置 Access-Control-Allow-Origin
的响应 header ,其值为 *
或在大多数情况下与请求 header 中发送的来源匹配的字符串,尽管它实际上取决于导致您的请求使用 CORS 的因素。您可能还需要提供具有值 *
的 Access-Control-Allow-Headers
响应 header 或请求中发送的各个 header 的名称,以逗号分隔。
看起来您的 Angular 调用正在触发 CORS,因为您正在设置不受支持的 Content-Type
简单请求 header :
推荐阅读- https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
关于javascript - 不能使用 angular ajax,因为它显示 No 'Access-Control-Allow-Origin' 。但是可以使用 xmlhttprequest 和 jquery 3x 来做到这一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40148411/