使用 D3 v5 中的授权 header 获取 JSON 数据

Fetch JSON data using Authorization header in D3 v5

我正在 d3.js v5.8.2 中处理一些图表,我想加载 JSON 我从需要授权的 API 请求中获得的数据 header.我试过类似的东西:

d3.json('url')
  .header("Authorization", "Bearer 7tsBVpsiYT")
  .get(function(error, data) {
    // callback
    console.log(data);
  });

我收到以下错误消息:

Uncaught TypeError: d3.json(...).header is not a function

由于 D3 v5 使用 Fetch API 替代先前版本使用的 XMLHttpRequest,因此需要对 d3.json() 的 API 进行一些更改。来自文档:

# d3.json(input[, init]) <>

Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.

您现在必须通过 RequestInit object 传递 Authorization header,后者作为可选的第二个参数传递给 d3.json()。正如 Mike Bostock 在他的基本演示 Fetch with Basic Auth 中解释的那样,这可以使用本机 Fetch API:

fetch("https://httpbin.org/basic-auth/user/passwd", {
  headers: new Headers({
    "Authorization": `Basic ${base64.encode(`${login}:${password}`)}`
  }),
}).then(response => {
  if (!response.ok) throw new Error(response.status);
  return response.json();
});

查看 d3.json()source 可以注意到上面的代码基本上等同于 D3 在执行 d3.json 时在内部所做的事情。因此,代码可以重写为:

d3.json("https://httpbin.org/basic-auth/user/passwd", {
  headers: new Headers({
    "Authorization": `Basic ${base64.encode(`${login}:${password}`)}`
  }),
}).then(json => { /* do something */ });