I have a static website, hosted on Azure (with free plan). The following is the structure of my website:
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.