0

I created a sample text file called sample.txt with a line of text like this:

I am a sample text file

And then in the same Visual Studio Code, I have the API.html file:

var textButton = document.getElementById('getText');
    textButton.addEventListener('click', getText);

    function getText() {
        fetch('sample.txt')
        // Fetch returns a promise
        .then(function(res) {
            console.log(res);
        })
    }

When I run it, the browser said paused on promise rejection. Type Error: Failed to fetch

  • Did it say anything else? Maybe a stack of CORS related error messages in the Console? What does the Network tab show? Does it make the request at all? Does it get a response? What HTTP status code does it show? Prediction: [duplicate of this](https://stackoverflow.com/questions/57236932/cross-origin-requests-are-only-supported-for-protocol-schemes-what-can-i-do) (but not enough information to tell for sure yet) – Quentin Dec 04 '19 at 14:57
  • It means you had an issue with querying the file. You need to catch the promise to see the error. My guess would be that you tried to use the fetch method with your html file opened from the `file://` protocol – Seblor Dec 04 '19 at 14:57
  • 1
    https://stackoverflow.com/questions/50007055/fetch-request-to-local-file-not-working – GammaGames Dec 04 '19 at 14:57
  • You are trying to fetch a local file. Fetch is an interface to HTTP, you can't simply fetch a local file. You need a server serving these local or otherwise – sinanspd Dec 04 '19 at 14:58

0 Answers0