如何使用JavaScript(外部域)解析RSS源?

我需要解析RSS提要并在HTML页面显示已解析的详细信息.

找到的解决方

How to parse an RSS feed using JavaScript?一个非常相似的问题,我跟着它.

使用上面的问题,我构建了以下代码.

<script>
  $(document).ready(function() {
    //Feed to parse
    var Feed = "https://Feeds.Feedburner.com/raymondcamdensblog?format=xml";

    $.ajax(Feed,{
        accepts:{
            xml:"application/RSS+xml"
        },dataType:"xml",success:function(data) {
            //Credit: https://stackoverflow.com/questions/10943544/how-to-parse-an-RSS-Feed-using-javascript

            $(data).find("item").each(function () { // or "item" or whatever suits your Feed
                var el = $(this);
                document.write("------------------------");
                document.write("title      : " + el.find("title").text());
                document.write("link       : " + el.find("link").text());
                document.write("description: " + el.find("description").text());
            });


        }   
    });

});
</script>

错误

Failed to load
07001: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘07002’ is therefore not allowed access.

我需要的

如何更改我的代码以使用JavaScript读取RSS源而不会出现上述错误

解决方法

由于 same-origin policy,您收到了该错误.请参阅下文和/或阅读 MDN的完整文章

For security reasons,browsers restrict cross-origin HTTP requests
initiated from within scripts. For example,XMLHttpRequest and the
Fetch API follow the same-origin policy. This means that a web
application using those APIs can only request HTTP resources from the
same origin
the application was loaded from,unless the response
from the other origin includes the right CORS headers.

所以你的脚本正在制作一个跨源HTTP请求(通过jQuery.ajax()使用XMLHttpRequest)到https://feeds.feedburner.com/raymondcamdensblog?format=xml,但是FeedBurner没有设置Access-Control-Allow-Origin的CORS头,因此你得到了“失败”加载……“错误. (但即使标题已设置,如果它不包含您的来源(localhost或some-domain.com),您仍会得到相同的错误.)

那么如何更改代码以使用JavaScript读取RSS源而不会出现该错误

>使用第三方Web服务,就像@ Saeed建议的那样.
>创建一个服务器端脚本(例如,使用PHP),该脚本获取内容并向该脚本发出AJAX请求,而不是直接从FeedBurner或实际源URL请求它.请参阅下面的简单示例.
>如果我真的不得不这样做,我可能会要求FeedBurner设置合适的CORS标头……

用于获取Feed内容的非常简单的PHP脚本示例:

<?PHP
// Set the Feed URL.
$Feed_url = 'https://Feeds.Feedburner.com/raymondcamdensblog?format=xml';

// Fetch the content.
// See http://PHP.net/manual/en/function.file-get-contents.PHP for more
// information about the file_get_contents() function.
$content = file_get_contents( $Feed_url );

// Set the Content-Type header.
header( 'Content-Type: application/RSS+xml' );

// display the content and exit.
echo $content;
exit;
?>

例如,您可以将其保存到fetch-Feed.PHP,然后在JavaScript / jQuery脚本代码中,更改Feed变量的值,如下所示:

var Feed = "http://localhost/path/to/fetch-Feed.PHP";

这样(即使用您自己的服务器端脚本),您至少可以确保浏览器始终授予您的XMLHttpRequest(或AJAX)请求. (即你不会得到“No’Access-Control-Allow-Origin’标题错误)

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...