1

I have an HTML file ( suppose "myHTML.html") and a local text file from which I want to load content and attach it to myHTML.

My problem is that whenever I try to use this code:

    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;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

which I've seen in a couple of threads here to read locally from text file, it works fine with VS-code and liveserver, but when I open myHtml directly with chrome without VS-code I get errors that say:

"Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load", 

"Access to XMLHttpRequest from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https"

"Failed to load resource: net::ERR_FAILED"

Does anyone have any solution to this?

Ori Lev
  • 31
  • 5
  • 1
    The solution is to use a server. You cannot make a GET request without a server because the server is what responds to a GET request. All you need is a basic Apache installation. (also, using `XMLHttpRequest` by definition isn't about opening local files, unless local means "on the same server") –  May 01 '20 at 10:04
  • The only way to actually read a local file is to use an ``, then manually select the file from the hard drive. Not what you want, I assume. –  May 01 '20 at 10:07
  • @ChrisG You assume right – Ori Lev May 01 '20 at 10:16
  • @ChrisG What about loading the inner HTML of an external local html file to the current html file? – Ori Lev May 01 '20 at 10:19
  • Doesn't matter if its HTML or txt or Egyptian hieroglyphs. You cannot do any of this with a flle directly opened in the browser. Just install Apache. (The only thing that will work is include a local `.js` file via ` –  May 01 '20 at 10:22

0 Answers0