Javascript Access-Control-Allow-Headers 不允许 X-Requested-With
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29344284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
X-Requested-With is not allowed by Access-Control-Allow-Headers
提问by Mark Preston
I am developing one system. In that system there is one add item to cart functionality. In that functionality, I am using Jquery $.ajax used. But online server I have facing this error -
我正在开发一个系统。在该系统中,有一项将商品添加到购物车功能。在该功能中,我使用了 Jquery $.ajax。但是在线服务器我遇到了这个错误 -
"XMLHttpRequest cannot load domain name/add_to_cart.php?item_id=3&hotel_id=2. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers."
“XMLHttpRequest 无法加载域名/add_to_cart.php?item_id=3&hotel_id=2。Access-Control-Allow-Headers 不允许请求标头字段 X-Requested-With。”
Can any help me how to solve this error.
任何人都可以帮助我如何解决此错误。
I am using this jquery code
我正在使用这个 jquery 代码
$(document).on('click', '.ordering_btn', function(){
var item_id = $(this).data('value');
var hotel_id = "<?php echo $hotel_id; ?>";
$.ajax({
type: 'GET',
url: 'add_to_cart.php?item_id='+item_id+'&hotel_id='+hotel_id+'',
contentType: 'text/plain',
xhrFields: {
withCredentials: false
},
headers: {
"Access-Control-Allow-Headers": "X-Requested-With",
"X-Requested-With": "XMLHttpRequest"
},
success: function(data) {
$('#cart_msg').css('display', 'none');
$('#cart_item').html(data);
console.log(data);
},
error: function() {
}
});
});
回答by AKhil N
The error can be fixed by adding
可以通过添加来修复错误
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
in the server where ajax call leads to....
在ajax调用导致的服务器中......
回答by Quentin
Remove this:
删除这个:
headers: {
"Access-Control-Allow-Headers": "X-Requested-With",
"X-Requested-With": "XMLHttpRequest"
},
Access-Control-Allow-Headersis a responseheader, not a request header.
Access-Control-Allow-Headers是响应头,而不是请求头。
The server you are making the request to does not allow X-Requested-With.
您向其发出请求的服务器不允许X-Requested-With。

