最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to parse an RSS feed using JavaScript (External Domain)? - Stack Overflow

programmeradmin2浏览0评论

Question

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

Solution I Found

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

Using above question, I build the following code.

 <script>
  $(document).ready(function() {
    //feed to parse
    var feed = "";

    $.ajax(feed, {
        accepts:{
            xml:"application/rss+xml"
        },
        dataType:"xml",
        success:function(data) {
            //Credit: 

            $(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 : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

What I need

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

Question

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

Solution I Found

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

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://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>

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.

What I need

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

Share Improve this question asked Aug 2, 2018 at 7:21 I am the Most Stupid PersonI am the Most Stupid Person 3,5759 gold badges25 silver badges49 bronze badges 1
  • To respond precisely your question: How can I change my code to read RSS feeds using JavaScript without getting above error? Unfortunately, there is nothing we can do with JavaScript (in browsers), except if you have a browser older than these developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… because the restriction is made by the browsers. – Emeeus Commented Aug 9, 2018 at 17:39
Add a comment  | 

4 Answers 4

Reset to default 8

You could use something like https://rss2json.com. It parses the feed to json for 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);
  }
});

You're getting that error because of the same-origin policy. See below and/or read the full article at 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.

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.)

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

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

  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.

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


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

<?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:

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)

You can also use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:

// Example for jquery.rss
$("#your-div").rss("https://feeds.feedburner.com/raymondcamdensblog?format=xml", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "https://feeds.feedburner.com/raymondcamdensblog?format=xml",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论