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?
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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With