0

I have a static website, hosted on Azure (with free plan). The following is the structure of my website:

enter image description here

Goal: I want that the webpage all-travel-blogs.html display the titles of all the travel blogs present inside the folder travel-blogs. To achieve this, I have the following javascript present in the file bloglist.js file:

function getBlogList() {
   var blogsFolder = './travel-blogs';
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
       if (xhr.readyState === 4) {
           if (xhr.status === 200) {
               var blogList = document.getElementById('blogList');
               var blogFiles = xhr.responseText.split('\n');
               var blogHTML = '';
               for (var i = 0; i < blogFiles.length; i++) {
                   if (blogFiles[i]) {
                       var blogTitle = getBlogTitle(blogFiles[i]);
                       var blogIntro = getBlogIntro(blogFiles[i]);
                       blogHTML += '<div><a href="' + blogsFolder + '/' + blogFiles[i] + '">' + blogTitle + '</a><p>' + blogIntro + '</p></div>';
                   }
               }
               blogList.innerHTML = blogHTML;
           } else {
               console.error('Failed to load blog files');
           }
       }
   };
   xhr.open('GET', blogsFolder, true);
   xhr.send();
}

function displayBlogList() {
   getBlogList();
}

function getBlogTitle(blogFile) {
   // Extract the title from the file name
   return blogFile.substring(0, blogFile.indexOf('.html'));
}

function getBlogIntro(blogFile) {
   // Get the first <p> element from the blog file
   var xhr = new XMLHttpRequest();
   xhr.open('GET', './travel-blogs/' + blogFile, false);
   xhr.send();
   var blogHTML = xhr.responseText;
   var parser = new DOMParser();
   var doc = parser.parseFromString(blogHTML, 'text/html');
   return doc.querySelector('p').innerHTML;
}

Code of the HTML Page to list all Travel blogs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Travel Blog List</title>
    <script src="./bloglist.js"></script>
</head>
<body onload="displayBlogList()">
    <h1>Travel Blog List</h1>
    <div id="blogList"></div>
</body>
</html>

PROBLEM: Since, the webpage was not displaying the list of blogs, I opened the Inspect webpage and found that I am getting following errors:

Access to XMLHttpRequest at 'file:///C:/github-client/Website/Eterna-Bootstrap-Theme-based-website/blogs/blogs/travel-blogs' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

enter image description here

UPDATE:

As per the suggestion, I installed the Live Server extension to test running the webpage on a local server. But still it is not working as shown in the screenshot below:

enter image description here

skm
  • 5,015
  • 8
  • 43
  • 104
  • 1
    "I have a static website, hosted on Azure (with free plan)" — The error message indicates that you are testing it by loading the files from your hard disk directly into the browser and **not** using Azure (maybe you plan to use Azure for your production environment, but you aren't using it for the test that is causing you problems). – Quentin Apr 27 '23 at 10:04
  • @Quentin: Even at Azure, it does not work. For testing, I installed the Live Server extension in Visual studio and tried to run the Webpage on the localhost, still it did not work. I have provided a new screenshot. – skm Apr 27 '23 at 13:14
  • 1
    Those are a completely different set of error messages indicating a completely different problem. Or, in this case, two completely different problems. 404 Not Found means the URL is wrong. Either (a) Your logic for calculating the URL based on the contents of ./travel-blogs is wrong or (b) that URL doesn't return the data you expect. There's no way for us to debug it with the information you've provided. (So the question should remain closed). – Quentin Apr 27 '23 at 15:54
  • 1
    Your second problem is a [FAQ](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Quentin Apr 27 '23 at 15:55

2 Answers2

0

The error message you mentioned indicates that the browser is blocking access to a file loaded by Azure Static Web App from the local file system due to the absence of the Access-Control-Allow-Origin header. This happens because of the CORS (Cross-Origin Resource Sharing) specification, which prevents browsers from accessing resources from other origins (such as different domains or file systems) without permission from the server.

Using Azure, you can set up global headers to ensure that our requests are sent to the server in accordance with CORS rules.

Example:

{
  "globalHeaders": {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS"
  }
}

I'm not sure why your Azure web app is attempting to load content using the file:// protocol (see: file://C:/github... in error message). This is an incorrect approach for any website, as it only works on a local machine. Unfortunately, I have not had the opportunity to test this behavior on Azure. My answer is solely based on my web development experience.

rozsazoltan
  • 2,831
  • 2
  • 7
  • 20
  • Since my website is hosted as Static website on Azure (since it's free), can I use web server? – skm Apr 27 '23 at 08:58
  • I have modified my answer. --- In the original wording, I wanted to emphasize that the `file://` protocol has never been appropriate for a website because it only works on the server machine. If you try to access the website from another machine, it won't be able to find the file. Instead, the `http://` protocol should be used. --- With Azure, there is no need for an additional web server. I just mentioned an example that is capable of serving the `http://` protocol. – rozsazoltan Apr 27 '23 at 10:04
  • I have rephrased my answer to give more attention to explaining CORS rules. Nevertheless, I still do not understand why Azure web app needs to use the `file://` protocol. Why can't it access another HTML file/folder with the `http://` protocol? – rozsazoltan Apr 27 '23 at 10:04
  • 1
    "I'm not sure why your Azure web app is attempting to load content using the file:// protocol" — The only explanation I can think of, given the code shown, is that the OP is experiencing his problem when testing locally before deploying to Azure. – Quentin Apr 27 '23 at 10:06
  • @Quentin: Right. The screenshots that I have posted are taken while testing locally. Once the things work fine locally then, I commit my changes to Azure. – skm Apr 27 '23 at 12:40
  • @rozsazoltan: I tried to run using a local server but still it not working. I have provided an Update with new screenshot in my original post. – skm Apr 27 '23 at 13:13
  • If I see it correctly, you accidentally inserted ` ` at the end of the link. As a result, the page cannot find the file on the path and displays a 404 error code. – rozsazoltan Apr 27 '23 at 13:31
-2

try to insert the data you would like in a div example: let my_data = "test"; document.getElementById("div-id").innerHTML = my_data;

andi
  • 23
  • 6