0

I can't seem to read local files using the fetch api, here's my code:

fetch('sometext.txt')
    .then(res => {
        return res.text()
    }).then(text => {
        console.log(text)
    });

It gave me a "CORS request not http". So I looked up for solutions and changed the mode to "no-cors". But I can't access the text because of the mode "no-cors".

fetch('sometext.txt', { mode: 'no-cors' })
    .then(res => {
        return res.text()
    }).then(text => {
        console.log(text)
    });

The console.log(text) merely prints out an empty string.

Are there ways to fix it?

Qiyoudaoyi
  • 1
  • 1
  • 2
  • 1
    Create a form with file upload. onchange, capture the event.files and using reader you can read the file contents. Using fetch, you need to have a server setup. – Alaksandar Jesus Gene Jul 29 '21 at 10:02
  • 1
    To summarise the many duplicates: You can't read local files without user interaction through a file reader. (Because otherwise any website you visit could open, e.g. `file://C:/passwords.txt`) – DBS Jul 29 '21 at 10:05
  • 1
    @DBS, thanks so much for your help. As a beginner starting writing some front-end code, I was wondering if there are ways to open local files like how we can do in C or Python. And I did not take security into consideration, thanks for bringing that up for me. – Qiyoudaoyi Jul 31 '21 at 21:30

0 Answers0