【问题标题】:How to add Authorization Header while accessing JSON in D3如何在 D3 中访问 JSON 时添加授权标头
【发布时间】:2014-07-22 12:28:50
【问题描述】:

我正在使用D3 graphs 构建一些交互式仪表板。我可以使用静态 JSON 集成图形。现在我想从我正在运行的服务器中获取 JSON。我的服务器需要某种基本授权。

添加基本身份验证标头后,我可以在Restclient 中获取 XML 响应。但在 D3 中它不起作用。

我的 D3 是这样的……

d3.json("http://localhost:9001/***/rest/products", function(error, root) {
   var node = svg1.selectAll(".node")
  .data(bubble.nodes(classes(root))
  .filter(function(d) { return !d.children; }))
.enter().append("g")
  .attr("class", "node")
  .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

   node.append("title")
     .text(function(d) { return d.className + ": " + format(d.value); });

   node.append("circle")
    .attr("r", function(d) { return d.r; })
    .style("fill", function(d) { return color(d.packageName); });

   node.append("text")
    .attr("dy", ".3em")
    .style("text-anchor", "middle")
    .text(function(d) { return d.className.substring(0, d.r / 3); });
 });

它会给出403 Forbidden 错误,因为这里我没有添加Authentication header。

如何在 D3.json 中添加身份验证标头,以便我可以以 JSON 形式访问我的资源而不会出现任何权限被拒绝的问题。

【问题讨论】:

  • 你至少应该能够做到d3.json("http://username:password@localhost:9001/...")。

标签: javascript jquery json rest d3.js


【解决方案1】:

从 d3.v5 开始更新。来自:https://beta.observablehq.com/@mbostock/fetch-with-basic-auth

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 函数,这将更有帮助
  • 耸耸肩。不知道该告诉你什么。这就是函数作者所说的这样做。
【解决方案2】:

您可以使用#header 方法添加请求标头:

https://github.com/mbostock/d3/wiki/Requests#header

d3.json("http://localhost:9001/***/rest/products") .header("header-name", "header-value") .get(function(error, root) { // Your code here. })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多