我正在d3.js v5.8.2中的某些图表上工作,我想加载从需要授权标头的API请求中获取的JSON数据。我尝试过类似的东西:
d3.json('url')
.header("Authorization", "Bearer 7tsBVpsiYT")
.get(function(error, data) {
// callback
console.log(data);
});
我收到以下错误消息:
未捕获的TypeError:d3.json(...)。header不是函数
由于D3 v5使用Fetch API替代了以前版本使用的XMLHttpRequest
,因此d3.json()
的API需要稍作更改。从文档:
# d3。json(输入 [,init])<>
在指定的input 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();
});
查看source的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 */ });