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

时间:2020-12-07 04:54:05

Question

I need to parse an RSS feed and display the parsed details in an HTML page.

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

Solution I Found

找到的解决方案

How to parse an RSS feed using JavaScript? is a very similar question and I followed it.

如何使用JavaScript解析RSS提要?是一个非常相似的问题,我遵循它。

Using above question, I build the following code.

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

 <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: http://*.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>

The Error

错误

Failed to load https://feeds.feedburner.com/raymondcamdensblog?format=xml: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

无法加载https://feeds.feedburner.com/raymondcamdensblog?format=xml:请求的资源上没有“Access-Control-Allow-Origin”标头。因此不允许Origin'http:// localhost'访问。

What I need

我需要的

How can I change my code to read RSS feeds using JavaScript without getting above error?

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

3 个解决方案

#1


3  

You're getting that error because of the same-origin policy. See below and/or read the full article at MDN:

由于同源策略,您收到了该错误。请参阅下文和/或阅读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请求。例如,XMLHttpRequest和Fetch API遵循同源策略。这意味着使用这些API的Web应用程序只能从加载应用程序的同一源请求HTTP资源,除非来自其他来源的响应包含正确的CORS标头。

So your script is making a cross-origin HTTP request (which uses XMLHttpRequest through jQuery.ajax()) to https://feeds.feedburner.com/raymondcamdensblog?format=xml, but the CORS header of Access-Control-Allow-Origin is not being set by FeedBurner, therefore you get the "Failed to load ..." error. (But even if the header was set, if it didn't include your origin (localhost or some-domain.com), you'd still get the same error.)

因此,您的脚本正在制作跨源HTTP请求(通过jQuery.ajax()使用XMLHttpRequest)到https://feeds.feedburner.com/raymondcamdensblog?format=xml,但是Access-Control-Allow-的CORS标题Feed不是由FeedBurner设置的,因此您会收到“无法加载...”错误。 (但即使标题已设置,如果它不包含您的来源(localhost或some-domain.com),您仍会得到相同的错误。)

So how can you change your code to read the RSS feeds using JavaScript without getting that error?

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

  1. Use a third-party web service, just like what @Saeed suggested.

    使用第三方Web服务,就像@Saeed建议的那样。

  2. Create a server-side script (e.g. using PHP) that fetches the feed content and make AJAX requests to that script instead of directly requesting it from FeedBurner, or the actual source URL. See below for a simple example.

    创建一个服务器端脚本(例如,使用PHP),该脚本提取feed内容并向该脚本发出AJAX请求,而不是直接从FeedBurner或实际源URL请求它。请参阅下面的简单示例。

  3. If I really had to, I'd probably ask FeedBurner to set the appropriate CORS headers...

    如果我真的不得不这样做,我可能会要求FeedBurner设置合适的CORS标头......


Sample of a very simple PHP script for fetching the feed content:

用于获取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;
?>

So for example, you could save that to fetch-feed.php, and then in your JavaScript/jQuery script code, change the value of the feed variable like so:

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

var feed = "http://localhost/path/to/fetch-feed.php";

That way (i.e. using your own server-side script), you could at least be sure that the browser would always grant your XMLHttpRequest (or AJAX) request. (i.e. you wouldn't get the "No 'Access-Control-Allow-Origin' header" error)

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

#2


2  

You could use something like https://rss2json.com. It parses the feed to json for javascript:

你可以使用像https://rss2json.com这样的东西。它将json的feed解析为javascript:

var feedURL = "https://feeds.feedburner.com/raymondcamdensblog?format=xml";
$.ajax({
  type: 'GET',
  url: "https://api.rss2json.com/v1/api.json?rss_url=" + feedURL,
  dataType: 'jsonp',
  success: function(result) {
    console.log(result);
  }
});

#3


0  

It's a CORS related error. You are getting that error because the URL from where you are requesting data does not have CORS enabled. CORS stands for 'Cross-Origin Resource Sharing'. If CORS is enabled on a server, your browser will let you make requests to that server. Otherwise, it will not.

这是与CORS相关的错误。您收到该错误,因为您请求数据的URL未启用CORS。 CORS代表“跨源资源共享”。如果在服务器上启用了CORS,则浏览器将允许您向该服务器发出请求。否则,它不会。

https://feeds.feedburner.com/raymondcamdensblog?format=xml does not have CORS enabled, that's why your browser will not allow you to make ajax requests to that server. You can get around it by making the requests on your server and provide the data to the browser from your own server or a server that has CORS enabled.

https://feeds.feedburner.com/raymondcamdensblog?format=xml没有启用CORS,这就是为什么您的浏览器不允许您向该服务器发出Ajax请求的原因。您可以通过在服务器上发出请求并从您自己的服务器或启用了CORS的服务器向浏览器提供数据来解决此问题。

#1


3  

You're getting that error because of the same-origin policy. See below and/or read the full article at MDN:

由于同源策略,您收到了该错误。请参阅下文和/或阅读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请求。例如,XMLHttpRequest和Fetch API遵循同源策略。这意味着使用这些API的Web应用程序只能从加载应用程序的同一源请求HTTP资源,除非来自其他来源的响应包含正确的CORS标头。

So your script is making a cross-origin HTTP request (which uses XMLHttpRequest through jQuery.ajax()) to https://feeds.feedburner.com/raymondcamdensblog?format=xml, but the CORS header of Access-Control-Allow-Origin is not being set by FeedBurner, therefore you get the "Failed to load ..." error. (But even if the header was set, if it didn't include your origin (localhost or some-domain.com), you'd still get the same error.)

因此,您的脚本正在制作跨源HTTP请求(通过jQuery.ajax()使用XMLHttpRequest)到https://feeds.feedburner.com/raymondcamdensblog?format=xml,但是Access-Control-Allow-的CORS标题Feed不是由FeedBurner设置的,因此您会收到“无法加载...”错误。 (但即使标题已设置,如果它不包含您的来源(localhost或some-domain.com),您仍会得到相同的错误。)

So how can you change your code to read the RSS feeds using JavaScript without getting that error?

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

  1. Use a third-party web service, just like what @Saeed suggested.

    使用第三方Web服务,就像@Saeed建议的那样。

  2. Create a server-side script (e.g. using PHP) that fetches the feed content and make AJAX requests to that script instead of directly requesting it from FeedBurner, or the actual source URL. See below for a simple example.

    创建一个服务器端脚本(例如,使用PHP),该脚本提取feed内容并向该脚本发出AJAX请求,而不是直接从FeedBurner或实际源URL请求它。请参阅下面的简单示例。

  3. If I really had to, I'd probably ask FeedBurner to set the appropriate CORS headers...

    如果我真的不得不这样做,我可能会要求FeedBurner设置合适的CORS标头......


Sample of a very simple PHP script for fetching the feed content:

用于获取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;
?>

So for example, you could save that to fetch-feed.php, and then in your JavaScript/jQuery script code, change the value of the feed variable like so:

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

var feed = "http://localhost/path/to/fetch-feed.php";

That way (i.e. using your own server-side script), you could at least be sure that the browser would always grant your XMLHttpRequest (or AJAX) request. (i.e. you wouldn't get the "No 'Access-Control-Allow-Origin' header" error)

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

#2


2  

You could use something like https://rss2json.com. It parses the feed to json for javascript:

你可以使用像https://rss2json.com这样的东西。它将json的feed解析为javascript:

var feedURL = "https://feeds.feedburner.com/raymondcamdensblog?format=xml";
$.ajax({
  type: 'GET',
  url: "https://api.rss2json.com/v1/api.json?rss_url=" + feedURL,
  dataType: 'jsonp',
  success: function(result) {
    console.log(result);
  }
});

#3


0  

It's a CORS related error. You are getting that error because the URL from where you are requesting data does not have CORS enabled. CORS stands for 'Cross-Origin Resource Sharing'. If CORS is enabled on a server, your browser will let you make requests to that server. Otherwise, it will not.

这是与CORS相关的错误。您收到该错误,因为您请求数据的URL未启用CORS。 CORS代表“跨源资源共享”。如果在服务器上启用了CORS,则浏览器将允许您向该服务器发出请求。否则,它不会。

https://feeds.feedburner.com/raymondcamdensblog?format=xml does not have CORS enabled, that's why your browser will not allow you to make ajax requests to that server. You can get around it by making the requests on your server and provide the data to the browser from your own server or a server that has CORS enabled.

https://feeds.feedburner.com/raymondcamdensblog?format=xml没有启用CORS,这就是为什么您的浏览器不允许您向该服务器发出Ajax请求的原因。您可以通过在服务器上发出请求并从您自己的服务器或启用了CORS的服务器向浏览器提供数据来解决此问题。