1

I use the following code to read a file using fetch:

fetch('rest.txt', {mode: 'no-cors'})
      .then(response => response.text())
      .then(data=> console.log(data));

And in the browser console I get the following response instead of the text of the file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="./static/favicon.ico"/>
    <title>TRAINSET</title>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-91042619-2"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-91042619-2');
    </script>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  <script type="text/javascript" src="/app.js"></script></body>
</html>
<style>
html, body {
  max-width: 100% !important;
  overflow-x: hidden !important;
}
</style>

I tried the same thing yesterday and it worked fine but today it doesn't.

Can someone please help me with this?

8
  • what is the error ? Commented Jan 23, 2020 at 6:45
  • What happens if you try to retrieve the file directly by typing the URL into the browser's address bar? Commented Jan 23, 2020 at 6:48
  • I'm guessing "URL scheme "file" is not supported." you need to run the site on a web server, you cannot just open the file in a browser. Commented Jan 23, 2020 at 7:00
  • But i was able to read just two days back and I'm not able to today. Hows that possible Commented Jan 23, 2020 at 7:06
  • can you add "catch()" and show whats the error. Commented Jan 23, 2020 at 7:53

2 Answers 2

1

Strange, I've copied directly that code and run with http-server

  fetch('/rest.txt', {mode: 'no-cors'})
      .then(response => response.text())
      .then(data=> console.log(data)); 

and it works

Can you show all the context where that code is used?

Sign up to request clarification or add additional context in comments.

3 Comments

Do you get the text of file as output?
Is the problem with npm version?
1.yes 2.I don't use npm I just use that chunk of code
1

Just add var customData = require('./rest.txt'); in the starting. It solved the problem for me. Without this, fetch will not run if it's running on server. Without server running, fetch will work without this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.