我正在尝试对打开的Web服务器进行简单的API调用。这是我实现此目的的代码:
function main()
{
makeAPIcall_GET(
'https://icanhazdadjoke.com/', // URL
function(response) // callback function
{
console.log(response);
try{
var parsedResponse = JSON.parse(response);
}catch(e){
logError(e);
}
}
);
}
function makeAPIcall_GET(url, callback)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.send();
// handle success
xhr.onload = function(){
callback(xhr.responseText);
}
}
这是我收到的CORS政策错误:
Access to XMLHttpRequest at 'https://icanhazdadjoke.com/' from origin 'null'
has been blocked by CORS policy: Request header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.
我浏览了Internet,希望找到解决方案,但是我不得不说我不明白为什么这行不通!谢谢。