-2

[enter image description here][1]i was learning ajax . but when i tried fetching data from local file it showed me error due to cors.i tried installing allow-access control origin but it didnt work .please help me

this is my java script code


function loadData() {
  // Create an XHR Object
  const xhr = new XMLHttpRequest();

  // OPEN
  xhr.open('GET', '/data.txt', true);

  // console.log('READYSTATE', xhr.readyState);

  // Optional - Used for spinners/loaders
  xhr.onprogress = function(){
    console.log('READYSTATE', xhr.readyState);
  }

  xhr.onload = function(){
    console.log('READYSTATE', xhr.readyState);
    if(this.status === 200) {
      // console.log(this.responseText);
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }

  // xhr.onreadystatechange = function() {
  //   console.log('READYSTATE', xhr.readyState);
  //   if(this.status === 200 && this.readyState === 4){
  //     console.log(this.responseText);
  //   }
  // }

  xhr.onerror = function() {
    console.log('Request error...');
  }

  xhr.send();


    // readyState Values
    // 0: request not initialized 
    // 1: server connection established
    // 2: request received 
    // 3: processing request 
    // 4: request finished and response is ready


  // HTTP Statuses
  // 200: "OK"
  // 403: "Forbidden"
  // 404: "Not Found"
}```


[this the image of output which is showing error .][2]


  [1]: https://i.stack.imgur.com/4YOqJ.png
  [2]: https://i.stack.imgur.com/Bh1km.png
  • 2
    Yes, accessing a users local files via Ajax would be a very serious security issue. That's why it's blocked.. – Keith Jun 16 '20 at 11:27
  • What is the current error/response you get? Is the `data.txt` file hosted by a web-server? Note that `data.txt` is a relative path. Say you are on the page `http://localhost/foo/bar` then it will point to `http://localhost/foo/bar/data.txt`. If you want this to be an absolute path add a slash (`/data.txt`), which would yield a request to `http://localhost/data.txt`. – 3limin4t0r Jun 16 '20 at 11:29
  • @Keith i have attached the image of my output .and i have also added a slash but its still not working – Rishab jain Jun 16 '20 at 11:54

1 Answers1

0

If you want to persist data in your client, use localStorage.

If you want to download data from a data source, use a web service.
You can easily create a simple web server using Node and Express, for example (plenty of resources online), but this is beyond the scope of this answer.

narduw
  • 40
  • 1
  • 5