Fetch API cannot load and Uncaught (in promise) TypeError: Failed to fetch Errors in d3.js

Fetch API cannot load and Uncaught (in promise) TypeError: Failed to fetch Errors in d3.js

我知道 d3.JS 有更新,我一直在搜索 Internet 和堆栈溢出以获取有关加载外部 json 或 csv 文件的指导。我修改了获取数据的函数,但仍然收到 2 个错误:

错误 1:Fetch API 无法加载 错误 2:未捕获(承诺)TypeError:获取失败

我不确定是什么原因造成的。我尝试了一些与其他帖子不同的修改,但没有成功。任何帮助表示赞赏。

d3.csv('mydata.csv').then(function(data){

var canvas = d3.select('body').append('svg')
  .attr('width', 700)
  .attr('height', 700)

canvas.selectAll('rect')
   .data(data)
   .enter()
    .append('rect')
    .attr('width', function(d){
        return d.age * 10
    })
    .attr('height', 48)
    .attr('y', function(d, i){
        return i * 50
    })
    .attr('fill', 'orange')

canvas.selectAll('text')
  .data(data)
  .enter()
    .append('text')
    .attr('fill', 'blue')
    .attr('y', function(d, i){
        return i * 50 + 30
    })
    .text(function(d){
        return d.name
    })
})

确保您使用的是最新版本 D3 此外,如果您对 CORS 感到困惑,请尝试将您的数据文件上传到 Github GIST 并将原始 URL 用于 CSV 数据文件。 或者,如果您的数据位于不同的服务器中,您可以尝试此 https://cors-anywhere.herokuapp.com/ 后跟 data/csv URL.

在此处查看使用您的代码和要点的示例

d3.csv('https://gist.githubusercontent.com/radaatyr/732f30394301fdc1384e9d109db428cb/raw/407167e7cc69036076945a9f1a02deafb5c26163/mydata.csv').then(function(data){

var canvas = d3.select('body').append('svg')
  .attr('width', 700)
  .attr('height', 700)

canvas.selectAll('rect')
   .data(data)
   .enter()
    .append('rect')
    .attr('width', function(d){
        return d.age * 10
    })
    .attr('height', 48)
    .attr('y', function(d, i){
        return i * 50
    })
    .attr('fill', 'orange')

canvas.selectAll('text')
  .data(data)
  .enter()
    .append('text')
    .attr('fill', 'blue')
    .attr('y', function(d, i){
        return i * 50 + 30
    })
    .text(function(d){
        return d.name
    })
})
<script src="https://d3js.org/d3.v5.min.js"></script>