1

I have a problem with get json data from file. I have an error 404 (Not found) in console. I dont know what is wrong, when i put url instead of a file path its works

export const loadProducts = {
    init: function () {
        this.getFromJson();
    },

    getFromJson: function() {
        const request = new XMLHttpRequest();

        request.open('GET', '../data/products.json', true);

        request.onreadystatechange = function() {
            if (request.status == 200){
                console.log('data')
                const files = JSON.parse(request.response);
            } 
            else {
                console.log('connected, but API returned an error');
            }
        };

        request.onerror = function() {
            console.log('connection error');
        };

        request.send(); 
    }

}
  • 1
    XMLHttpRequest will not read from the file system -- it will try to read from `localhost` in this case. Do you need to read from the file system? – Explosion Pills Jul 24 '18 at 07:24
  • How are you opening / running this script; in a browser or console via node? – Phil Jul 24 '18 at 07:25
  • If you're going to use `onreadystatechange` you **must** check `request.readyState` is `4` (or `XMLHttpRequest.DONE`) before attempting to check `status` and `responseText` – Phil Jul 24 '18 at 07:27
  • Yes, I need read this from file system. – user8188335 Jul 24 '18 at 07:30
  • If you want to use file system, don't you want to try nodejs instead, refs: https://nodejs.org/api/fs.html ? it does provide file system api out of the box. refers to this question: there's thorough explanation on writing or reading files in one of the answer, https://stackoverflow.com/questions/371875/local-file-access-with-javascript – gema Jul 24 '18 at 07:55

1 Answers1

1

Try it. It works for me.

export const loadProducts = {
  init: function() {
    this.getFromJson();
  },

  getFromJson: function() {
    const request = new XMLHttpRequest();
    requeest.overrideMimeType("application/json");

    let path = 'file:///C:/folder/blah.json';

    request.open('GET', 'file:///C:/some/file.json', true);

    request.onreadystatechange = function() {
      if (request.readyState == 4 && request.status == "200") {
        console.log('data')
        const files = JSON.parse(request.response);
      } else {
        console.log('connected, but API returned an error');
      }
    };

    request.onerror = function() {
      console.log('connection error');
    };

    request.send();
  }

}

P.s. XMLHttpRequest works with file protocol. Read here

Kas Elvirov
  • 7,394
  • 4
  • 40
  • 62