Showing posts with label D3. Show all posts
Showing posts with label D3. Show all posts

Sunday, July 23, 2017

Loading CSV files using D3.js in Chrome Brower

When we try to load files (json,csv,tsv,dsv) files to javascript console in Chrome Browser:

d3.json('/opt/pupils_museum.json', function(data){console.log(data[0]); });

we receiving the following errors:


  1. XMLHttpRequest cannot load file://opt/pupils_museum.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
  2. XMLHttpRequest cannot load http://localhost:8888/pupils_museum.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

For the first error message, I consulted the stackoverflow link: https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local and the solution provided is :

Expose the files using a simple HTTP Server:

/opt/ $ python -m SimpleHTTPServer 8888
Serving HTTP on 0.0.0.0 port 8888 ...

Now we can try to access the file



Now, we try to access the json file from console:

d3.json('http://localhost:8888/pupils_museum.json', function(data){console.log(data[0]);});

We receive the second error message mentioned above. To solve this problem I have consulted the stackoverflow website: https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource

For this , we install the following chrome plugin: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US


Now we try to acces the csv file again from localhost:

d3.json('http://localhost:8888/pupils_museum.json', function(data){console.log(data[0]);});
Object {header: function, mimeType: function, responseType: function, response: function, get: function…}
VM244:1 Object {name: "Annie Bell", gender: "girl", age: 10, attending: true}age: 10attending: truegender: "girl"name: "Annie Bell"__proto__: Object


Success!!