Reputation: 75
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?
Upvotes: 5
Views: 12329
Reputation: 7101
Another possibility mentioned in How to launch html using Chrome at "--allow-file-access-from-files" mode? is to use a browser extension like Web Server for Chrome
Upvotes: 0
Reputation: 2511
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.
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.
Upvotes: 3