-2
    document.querySelector("#btn").addEventListener("click",loadData);

    function loadData(){
    const xhr = new XMLHttpRequest();

    console.log("READYSTAT",xhr.readyState)

    xhr.open("GET","trial.txt", true)

    xhr.onload = function(){
        if(this.status === 200){
            console.log(this.responseText)
        }
    }

This is the error

Access to XMLHttpRequest at 'file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

    xhr.send();
}
Dai
  • 141,631
  • 28
  • 261
  • 374
  • The error message is quite self-explanatory: you cannot use `XMLHttpRequest` or (`fetch`) when you open a `*.html` file from-disk. You will need to use a local webserver. – Dai May 31 '20 at 02:36

1 Answers1

0

XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. source

XMLHttpRequest (XHR) objects are used to interact with servers. source

from this

file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt

I am pretty sure that the URL in your browser is something like this file:///C:/Users/kenne/OneDrive/Desktop/javascript/index.html

So the requested URL trial.txt will request to file:///C:/Users/kenne/OneDrive/Desktop/javascript/trial.txt, obviously, there is no server here

Run a local HTTP server using python

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
oxidia
  • 196
  • 2
  • 5