【问题标题】:CORS no Acess-Control-Allow-Origin headerCORS 没有 Access-Control-Allow-Origin 标头
【发布时间】:2018-04-04 21:00:44
【问题描述】:

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

但尽管使用了 CORS,但我总是得到没有 Access-Control-Allow-Origin 标头。是我误解了 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();

提前致谢 新星

【问题讨论】:

    标签: javascript html xml cors


    【解决方案1】:

    你设置了header("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);
    

    【讨论】:

    • 您能解释一下如何设置标题吗?因为我认为 header(...) 是 php
    • 如果你没有在anime2you.de/feed 上使用php,你将需要在服务器上找到一些地方,可能是一个.htaccess 文件或apache 配置文件,这取决于你的服务器正在运行什么。在 IIS 中,如果它的窗口。
    • 服务器不是我的。它是一个包含网站 Rss 提要的页面。我想获取 xml 数据以在我的网站上显示提要。我无法控制anime2you
    • 添加了使用 jsonp 的替代解决方案。但是,如果anime2you.de/feed 无法返回 json,这可能不起作用。如果做不到这一点,您将不得不考虑使用 iframe,尽管我知道数据的格式不正确。你不能使用服务器端代码而不是javascript吗?然后您可以向anime2you.de/feed 发出http 请求并将响应格式化为您心中的内容
    • 问题是我根本不懂php。但我可以使用 Node.js。 JS.
    猜你喜欢
    • 2018-08-30
    • 2016-05-13
    • 2018-09-19
    • 2019-06-19
    • 2017-04-15
    • 2014-01-20
    • 2019-02-07
    • 2016-01-21
    • 1970-01-01
    相关资源
    最近更新 更多