Search code examples
javascripthtmlcssxmlrss

Fetch and Display RSS Feed on a Web Page


I'm currently working on a project where I need to fetch and display news from an RSS feed on a web page. I'm using the Fetch API in JavaScript to retrieve the data and parse it as XML. However, despite my efforts, I'm unable to display the news on my page. Here is the code I am using:

`

<div id="scroll-text">
    <div class="section">
        <div id="scroll-container"></div>
    </div>
</div>

<script>
    async function fetchRSS() {
        const proxyUrl = 'https://api.allorigins.win/get?url=';
        const targetUrl = 'https://safeonweb.be/fr/rss';
        const fetchUrl = `${proxyUrl}${encodeURIComponent(targetUrl)}`;
        
        try {
            console.log('Fetching URL:', fetchUrl); // Debugging 1: Log the request URL
            const response = await fetch(fetchUrl);
            const data = await response.json();
            
            console.log('Data fetched:', data); // Debugging 2: Log the raw data
            
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(data.contents, "application/xml");

            console.log('Parsed XML:', xmlDoc); // Debugging 3: Log the parsed XML

            const items = xmlDoc.querySelectorAll("item");
            const scrollContainer = document.getElementById('scroll-container');
            scrollContainer.innerHTML = '';

            items.forEach(item => {
                const title = item.querySelector("title").textContent;
                const link = item.querySelector("link").textContent;
                const description = item.querySelector("description").textContent;
                const pubDate = item.querySelector("pubDate").textContent;

                const newsItem = document.createElement('div');
                newsItem.classList.add('news-item');
                newsItem.innerHTML = `
                    <h3><a href="${link}" target="_blank">${title}</a></h3>
                    <p>${description}</p>
                    <small>${pubDate}</small>
                `;

                scrollContainer.appendChild(newsItem);
            });
        } catch (error) {
            console.error('Error fetching the RSS feed:', error);
        }
    }

    document.addEventListener('DOMContentLoaded', fetchRSS);
</script>

`

Issues Encountered:

The page remains blank and no news items are displayed. I have added debugging messages in the console, but I don't see any obvious errors. Observations:

The request URL seems correct. The response from the allorigins API contains the RSS data. XML parsing does not appear to be an issue, but nothing is displayed. Questions:

Am I using the Fetch API with the allorigins proxy correctly? Are there common pitfalls I should check for in this scenario? Any tips on how to improve this code to ensure the news items are displayed? Thanks in advance for your help!


Solution

  • You get XML so directly pass it on to the DOMParser (note that I changed to a more reliable proxy):

        async function fetchRSS() {
            const proxyUrl = 'https://corsproxy.io/?';
            const targetUrl = 'https://safeonweb.be/fr/rss';
            const fetchUrl = `${proxyUrl}${encodeURIComponent(targetUrl)}`;
            
            try {
                console.log('Fetching URL:', fetchUrl); // Debugging 1: Log the request URL
                const response = await fetch(fetchUrl);
                const data = await response.text();
                
                console.log('Data fetched:', data); // Debugging 2: Log the raw data
                
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(data, "application/xml");
    
                console.log('Parsed XML:', xmlDoc); // Debugging 3: Log the parsed XML
    
                const items = xmlDoc.querySelectorAll("item");
                const scrollContainer = document.getElementById('scroll-container');
                scrollContainer.innerHTML = '';
    
                items.forEach(item => {
                    const title = item.querySelector("title").textContent;
                    const link = item.querySelector("link").textContent;
                    const description = item.querySelector("description").textContent;
                    const pubDate = item.querySelector("pubDate").textContent;
    
                    const newsItem = document.createElement('div');
                    newsItem.classList.add('news-item');
                    newsItem.innerHTML = `
                        <h3><a href="${link}" target="_blank">${title}</a></h3>
                        <p>${description}</p>
                        <small>${pubDate}</small>
                    `;
    
                    scrollContainer.appendChild(newsItem);
                });
            } catch (error) {
                console.error('Error fetching the RSS feed:', error);
            }
        }
    
        document.addEventListener('DOMContentLoaded', fetchRSS);
    <div id="scroll-text">
        <div class="section">
            <div id="scroll-container"></div>
        </div>
    </div>