Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `fetch()` to display plain text in a web page [duplicate]

Using Javascript to display a string variable in an HTML page is easy:

<html>
<body>

<script>
text = "hello"
document.getElementById("demo").innerHTML = text
</script>

<p id="demo"></p>

</body>
</html>

However I would like to replace "hello" with the contents of a local file, say file.txt. I think this should be easily accomplished using Javascript's fetch() API but I'm running into problems. This,

<html>
<body>

<p id="demo"></p>

<script>
text = fetch('file.txt').then(response => response.text())
document.getElementById("demo").innerHTML = text
</script> 

</body>
</html>

will display [object Promise]. I guess I somehow must access the response object but I don't know how that is done.

like image 414
sammosummo Avatar asked Oct 21 '25 06:10

sammosummo


2 Answers

response.text() returns also a promise. So you have to add another then to get the text.

response.text().then(function (text) {
  // do something with the text response 
});
like image 167
Simtschy Avatar answered Oct 23 '25 19:10

Simtschy


text in your code is a promise, not text. You need to use the promise callback:

fetch('file.txt')
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text();
})
.then(text => {
    document.getElementById("demo").innerHTML = text;
})
.catch(error => {
    // Handle/report error
});
like image 33
T.J. Crowder Avatar answered Oct 23 '25 19:10

T.J. Crowder