Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch JSON data using Authorization header in D3 v5

I am working on some charts in d3.js v5.8.2 and I want to load JSON data that I get from an API request which needs an authorization header. I tried something like:

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

I get the following error message:

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

like image 987
galatia Avatar asked Oct 20 '25 07:10

galatia


1 Answers

Since D3 v5 uses the Fetch API as a replacement for the XMLHttpRequest which was used by prior versions the API for d3.json() needed to be changed a bit. From the docs:

# 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.

You now have to pass the Authorization header via the RequestInit object which is passed as the optional second argument to d3.json(). As Mike Bostock explains in his basic demo Fetch with Basic Auth this can be done using the native 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();
});

Looking at the source of d3.json() one notices that above code is basically equivalent to what D3 does internally while executing d3.json. Thus, the code can be rewritten as:

d3.json("https://httpbin.org/basic-auth/user/passwd", {
  headers: new Headers({
    "Authorization": `Basic ${base64.encode(`${login}:${password}`)}`
  }),
}).then(json => { /* do something */ });
like image 116
altocumulus Avatar answered Oct 24 '25 18:10

altocumulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!