0

I have spent hours just trying to access a json object stored as a local file in javascript. Basically I am trying to use the json file to initialise a js object with values from the json file. This needs to be done in Chrome. I know that people have had similar problems (relating to security) but I cannot find a way to do this.

The till.js file looks like this:

function Till(){
  var mydata = $.getJSON("/files/hipstercoffee.json")
  this.shop = mydata[0].shop;
  console.log(mydata[0].shop);
}

The json file looks like this:

[
  {
    "shop": "Coffshop",
    "address": "123 Happy Street",
    "prices": [
      {
        "Latte": 2.80,
        "Tea": 2.10
      }
    ]
  }
]

In a basic index.html file I have the following script tags:

<script type = "text/javascript" src = "src/till.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>  

I load up the index.html file and in the Chrome developer console I type:

var till = new Till();

The error message I get is:

XMLHttpRequest cannot load file:///files/coffee.json
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

How do I get round this problem?

jeebee
  • 53
  • 8
  • chrome does not work with ` file://` change to localhost or real server with CORS enabled – ewwink Aug 11 '17 at 13:41
  • the domain of your website needs to be the same as those of your ajax urls, try to access both through localhost – smarber Aug 11 '17 at 13:42
  • You're running on your local file system so brower security is much tighter around JS methods. You need to run on a webserver. You can quite easily install IIS or XAMPP – Rory McCrossan Aug 11 '17 at 13:44
  • you need a local server like express or simple run PHP server: php -S localhost:8000 Your problem is cross origin security(implemented in all browsers"). You can read more about this problem in first answer here: https://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht – Krzysztof Raciniewski Aug 11 '17 at 13:46
  • Will this work in Firefox then which doesn't have the same restrictions? I don't get an error but the object just looks like this: Object { readyState: 1, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), then: then(), 8 more… } – jeebee Aug 11 '17 at 15:55
  • Thanks for the help. I got round this by running the website on localhost using "sudo python2 -m SimpleHTTPServer 80" (from UBUNTU). – jeebee Aug 15 '17 at 22:04

0 Answers0