0
function readTextFile(file) {     
    var rawFile = new XMLHttpRequest();

    rawFile.open("GET", file, false);   
    rawFile.onreadystatechange = function () {   
        if(rawFile.readyState === 4) {   
            if(rawFile.status === 200 || rawFile.status == 0) {   
                var allText = rawFile.responseText;    

            }
        }
    }
    rawFile.send(null);
}


readTextFile('file:///C:/test.txt');

it errors with the message:

testini:41 Access to XMLHttpRequest at 'file:///C:/test.txt' from origin 'http://localhost:54862' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
mam
  • 87
  • 1
  • 9
  • 1
    Try to use the provided search engine: https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file – Higanbana Nov 25 '19 at 08:52
  • 4
    You can't access local drive using client side technology without using a [file input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) for security reasons. – Adrian Nov 25 '19 at 08:53

2 Answers2

2

I assume you use Google Chrome which which applies Same origin policy to file system too.

You can:

  • Use firefox which will allow the request
  • Start chrome with --disable-web-security enabled (you can do this by using a terminal). It's not advised and you should not navigate through other websites with this flag enabled.

If you don't particularly need to access the file system, you can install a local web server which will reply with Access-Control-Allow-Origin: * so that the server running on port 54862 will have access to your files.

vidu.sh
  • 537
  • 1
  • 3
  • 21
-1

This error means you need to enable CORS on your server listening.

For example here's how to do it in Node JS: https://dzone.com/articles/cors-in-node

CORS will allow your server to process Cross origin requests. Hope this helps

aPurpleDev
  • 123
  • 1
  • 12
  • This definitively isn't a node.js question. – Adrian Nov 25 '19 at 08:57
  • Yeah I provided the Node doc as example to support the reply, not knowing how the server listening is handled. Just trying to help here – aPurpleDev Nov 25 '19 at 08:58
  • The error explcitly says "_Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https._". OP is using `file://` here. Enabling CORS is not going to fix that. (If you even manage to enable it for your local file system.) – Ivar Nov 25 '19 at 09:00
  • Okay, thank you for explaining this to me. – aPurpleDev Nov 25 '19 at 09:08