user15974743
user15974743

Reputation:

Error when getting txt file using fetch()

I want to get the contents of this page, and store it an a variable.

I have the following code:

// fetch the txt file
const fileUrl = 'https://pastebin.pl/view/raw/2facc037'

fetch(fileUrl)
  .then( r => r.text() )
  .then( t => {var message = t} )

console.log(message)
<!DOCTYPE html>
<head>
    <title>Test Document</title>
</head>
<body>
    <h1>Open developer tools...</h1>
</body>
</html>

It gives an error. Why?

PS: I have a good reason why I want to store it an a variable

Upvotes: 0

Views: 745

Answers (1)

RCB
RCB

Reputation: 377

You're declaring the message variable only within the scope of the last then callback. Move the console log there to log the message:

// fetch the txt file
const fileUrl = 'https://pastebin.pl/view/raw/2facc037'

fetch(fileUrl)
  .then( r => r.text() )
  .then( t => {
      var message = t;
      console.log(message);
  } )

Upvotes: 2

Related Questions