CORS没有Acess-Control-Allow-Origin标头

时间:2017-11-21 21:00:25

标签: javascript html xml cors

在我的Javascript文件中,我想从此站点加载xml数据:https://www.anime2you.de/feed/

但是我总是得到一个没有Access-Control-Allow-Origin标头,尽管使用CORS。我是否误解了CORS的概念/用法或网站是否有错?

我的代码:

var feeds = ["https://www.anime2you.de/feed/"];

var createCORSRequest = function(method, url) {
  var xhr = new XMLHttpRequest();
   if ("withCredentials" in xhr) {
   // Most browsers.
    xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
     // IE8 & IE9
       xhr = new XDomainRequest();
       xhr.open(method, url);
   } else {
     // CORS not supported.
       xhr = null;
   }
 return xhr;
};

var url = 'https://www.anime2you.de/feed/';
var method = 'GET';
var xhr = createCORSRequest(method, url);

xhr.onload = function() {
  alert("success");
};

xhr.onerror = function() {
  alert("fail");
};

xhr.send();

提前致谢 新星

1 个答案:

答案 0 :(得分:2)

您是否设置了标题(“Access-Control-Allow-Origin:*”);在您要求的脚本上? https://www.anime2you.de/feed/如果您使用带有通配符的Access-Control-Allow-Origin,则在

中将凭据设置为false
xhr.withCredentials = false;

如果您可以设置发出请求的服务器的域名,即

header("Access-Control-Allow-Origin: http://domain-where-js-sits"); 

然后你可以这样做:

xhr.withCredentials = true;

并设置其他标题:

Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type 

另一种方法是使用jsonp - 这可能不适合你,因为响应需要在json中:

function response(data) {
    edit the returned data here
}

var script = document.createElement('script');
script.src = 'https://www.anime2you.de/feed/?callback-response';
document.body.appendChild(script);