Javascript ajax请求的CORS错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36568923/
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
CORS error with ajax request
提问by xenurs
i'm doing this request in ajax but i still have this following error about CORS: XMLHttpRequest cannot load https://cubber.zendesk.com/api/v2/organizations/37520251/users.json. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. Can you help me pls ( i have seen many topic and i still don't understand why it is not working
我正在 ajax 中执行此请求,但我仍然有以下关于 CORS 的错误: XMLHttpRequest 无法加载https://cubber.zendesk.com/api/v2/organizations/37520251/users.json。预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Access-Control-Allow-Origin。你能帮我吗(我看过很多话题,但我仍然不明白为什么它不起作用
function afficheorga(a){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+a+"/organizations.json",
type: 'GET',
dataType: 'json',
cors: true ,
contentType:'application/json',
secure: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
console.log(data.organizations[0].name);
var organisation = data.organizations[0].name;
$("#company").text(organisation);
}
})
}
采纳答案by Paul Fitzgerald
You could get around this by using jsonp
. Change dataType
to jsonp
so your GET
request should be as follows
你可以通过使用来解决这个问题jsonp
。更改dataType
为jsonp
因此您的GET
请求应如下
function afficheorga(a){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+a+"/organizations.json",
type: 'GET',
dataType: 'jsonp',
cors: true ,
contentType:'application/json',
secure: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
console.log(data.organizations[0].name);
var organisation = data.organizations[0].name;
$("#company").text(organisation);
}
})
}