Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly load local JSON in D3?

Tags:

json

d3.js

Trying to load a local .json-file from the same folder in D3 (and logging it to the console), but there are two errors in the console:

d3.v5.js:5908 Fetch API cannot load [buildings.json - file]. URL scheme must be "http" or "https" for CORS request. json @ d3.v5.js:5908 (anonymous) @ index.html:10

d3.v5.js:5908 Uncaught (in promise) TypeError: Failed to fetch at Object.json (d3.v5.js:5908) at index.html:10 json @ d3.v5.js:5908 (anonymous) @ index.html:10 Promise.then (async) (anonymous) @ index.html:10

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://d3js.org/d3.v5.js"></script>
  </head>
  <body>
    <script>
d3.json("buildings.json").then(data => console.log(data))
    </script>
  </body>
</html>

Does anybody see the reason & have a solution?

like image 850
nikbad Avatar asked Oct 16 '22 12:10

nikbad


1 Answers

d3.json uses fetch.

export default function(input, init) {
  return fetch(input, init).then(responseJson);
}

https://github.com/d3/d3-fetch/blob/master/src/json.js

So you are dealing with the same problem described in these SO posts.

  • Importing local json file using d3.json does not work

  • "Cross origin requests are only supported for HTTP." error when loading a local file

  • Fetch API cannot load file:///C:/Users/woshi/Desktop/P5/p5/JSON/birds.json. URL scheme must be "http" or "https" for CORS request

You are facing a problem with cross origin resource sharing which is a security feature by your browser.

Two options two avoid this:

  1. use a webserver. To just run a simple webserver for your static html/js files something like the npm http-server (https://www.npmjs.com/package/http-server) could be used

  2. Change your chrome startup parameters and let it know that you want to ignore this security feature. You can do this by changing your startup configuration for example like this

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="%LOCALAPPDATA%\Google\Chrome\User Data\development"

The parameters --disable-web-security --user-data-dir are the important part here.

Note: Just use this for development. You allow cross origin requests by this for all websites you visit.

like image 86
MicFin Avatar answered Oct 21 '22 04:10

MicFin