javascript fetch command does not display the content on the html page

Viewed 20

I have a simple text file in the same directory as HTML file , I used the fetch command in javascript to display the text file content in the page div section when the loading of the page finish

however, my code doesn't work and nothing has been displayed, my question is does the fetch command suitable for such a task or should I use filereader ?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript"  defer>     
 const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"

console.log(myfile);

async function getTextFile1() {
  try {
  
    const response = await fetch(myfile, { mode: 'no-cors' }); 
    const fileText = await response.text();
    //console.log(window.location);
    //console.log(window.location.href);
    
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
  } catch (error) {
    console.log(error);
  }
 }
 

window.onload = getTextFile1;
</script> 
</head>
<body>
<div  >should be placed here    </div>
   <div id="about_layer">
   </div>
</body>
</html>

1 Answers

There is nothing wrong with your code , just try running your html file using development server .

You can use Live Server visual studio code extension for that.

Related