我正在 d3.js v5.8.2 中处理一些图表,我想加载从需要授权标头的 API 请求中获取的 JSON 数据。我试过类似的东西:
d3.json('url')
.header("Authorization", "Bearer 7tsBVpsiYT")
.get(function(error, data) {
// callback
console.log(data);
});
我收到以下错误消息:
未捕获的类型错误:d3.json(...).header 不是函数
由于 D3 v5 使用Fetch API作为替代XMLHttpRequest
先前版本使用的 API,d3.json()
因此需要稍微更改API 。从文档:
# d3。json (输入[, init ]) <>
获取指定输入URL处的 JSON 文件。如果指定了init,则将其传递给对fetch的底层调用;有关允许的字段,请参阅RequestInit。
您现在必须Authorization
通过RequestInit
对象传递标头,该对象作为可选的第二个参数传递给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()
一个告示,上面的代码基本上相当于什么呢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 */ });
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句