gpt4 book ai didi

json - 如何在 D3 中正确加载本地 JSON?

转载 作者:行者123 更新时间:2023-12-04 08:30:23 26 4
gpt4 key购买 nike

尝试从 D3 中的同一文件夹加载本地 .json 文件(并将其记录到控制台),但控制台中有两个错误:

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>


有没有人看到原因并有解决方案?

最佳答案

d3.json 使用 fetch

export default function(input, init) {
return fetch(input, init).then(responseJson);
}
https://github.com/d3/d3-fetch/blob/master/src/json.js
因此,您正在处理这些 SO 帖子中描述的相同问题。
  • 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.

    关于json - 如何在 D3 中正确加载本地 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528018/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com