如何在D3中访问JSON时添加Authorization Header

Fre*_*ded 3 javascript rest jquery json d3.js

我正在研究D3图表来构建一些交互式仪表板.我可以使用静态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); });
 });
Run Code Online (Sandbox Code Playgroud)

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

如何在D3.json中添加身份验证标头,以便我可以在没有任何权限被拒绝的情况下以JSON格式访问我的资源.

ben*_*les 7

您可以使用以下#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. })