Unlocking access: Bearer Authentication for AmCharts JS

I am currently working with a .NET Core server that has an API from which I need to request data using the default loading method in AmCharts.

The endpoint on the server side is structured like this:

[Authorize]
    public class StocksController : ApiController {
        [HttpGet("{id}")]
        public async Task<ActionResult<string>> GetStockIntraday1min(string id) {
            return await Mediator.Send(new GetStockHistoryQuery { Symbol = id, Interval = "1min" });
        }
    }
}

Using a JS Fetch request, I can successfully retrieve the data, as shown in the example below.

let response = await fetch("api/stocks/getstockintraday1min/tsla", {
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
    }
})

However, when I attempt to achieve the same result using AmCharts, I encounter a 401 Unauthorized Request error in the FireFox console, as highlighted below:

XHR GET https://localhost:44397/api/stocks/getstockintraday1min/tsla [HTTP/2 401 Unauthorized 8ms]

Following the guidance from the AmCharts documentation, specifically regarding setting up request headers with the authorization token, I have made several attempts which have been unsuccessful. Here is a snippet of what I have tried:

// Apply themes
am4core.useTheme(am4themes_animated) // Animations
am4core.useTheme(am4themes_dark) // Colors

// Create chart
let chart = am4core.create("chartdiv", am4charts.XYChart)
chart.padding(5, 15, 5, 15)
// Add data source information
console.log(authToken) // To verify token actually is set
let myHeaders = new Headers({
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": `Bearer ${authToken}`
})
chart.dataSource.url = "api/stocks/getstockintraday1min/tsla"
chart.dataSource.requestOptions.requestHeaders = myHeaders
// chart.dataSource.requestOptions.withCredentials = true // seems to do nothing?
chart.dataSource.parser = new am4core.JSONParser()

Despite my efforts, I have been unable to get the Authorization header to work properly. I have also attempted variations, as shown below:

// Apply themes
am4core.useTheme(am4themes_animated) // Animations
am4core.useTheme(am4themes_dark) // Colors

// Create chart
let chart = am4core.create("chartdiv", am4charts.XYChart)
chart.padding(5, 15, 5, 15)
// Add data source information
console.log(authToken) // To verify token actually is set
chart.dataSource.url = "api/stocks/getstockintraday1min/tsla"
chart.dataSource.requestOptions.requestHeaders = [{
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": `Bearer ${authToken}`
}]
// chart.dataSource.requestOptions.withCredentials = true // seems to do nothing?
chart.dataSource.parser = new am4core.JSONParser()

Unfortunately, none of the options with just the Authorization: Bearer row or without the [] surrounding the JSON Object have been successful.

Despite searching various resources, including YouTube, I have not been able to find a solution. Any assistance in identifying what I may be missing would be greatly appreciated.

Answer №1

After some research, I discovered that the DataSource object requires an array of requestHeaders for its requestOptions. To ensure that your headers are read correctly, you should add them in this manner:

chart.dataSource.requestOptions.requestHeaders = [
    {key: "Authorization", value: `Bearer ${accessToken}`}
]

Although the documentation mentions this, I didn't fully grasp it when initially reading it. Documentation reference:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to link multiple GET requests and combine their results into an array in JavaScript/Node?

The current code is a bit messy, and I'm still unsure about the then method. What each 'get' call returns: An array with some, but not all, results. What I need: To pass two different URIs, concatenate the results of both, and then expor ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Express server failing to serve js and css files

Currently, I'm working on a ReactJS project with React Router implemented. When attempting to access /dashboard/stream, the server is returning the index.html file successfully. However, there are 301 errors for the CSS and JS files, resulting in noth ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

Sending an array of JSON objects using jQuery is a simple and straightforward process. By

I'm currently facing a challenge while working on my web page - I am struggling to send an Array of JSON objects to my PHP backend script. Below is the JavaScript code I have been using (with jQuery): var toSend = new Array(); ...

I have experimented with both POST and GET methods in Node.js, exploring a variety

After creating a login page with a GET form, the server code includes: app.use(express.static(path.join(__dirname, 'public'))); I am facing an issue trying to implement a POST request. When I use "POST", it gives me a "CANNOT / PO ...

Guide to transferring filtered data to the controller

As I work on designing a user interface for managing project applications, one of the key functionalities is the ability to filter applications by their type. Within the UI, there is a prominent button labeled select ALL which, when clicked, is meant to se ...

Sliding in images with JQuery

I need help with animating the slide-in effect of 7 "card" images from the left to the center of the screen. I attempted to achieve this using the following code: function FetchCards() { $("#pack").css('margin-left', 0); $("#pack").css(& ...

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

AngularJS making use of multiple checkboxes to filter data from a nested JSON structure

Hi everyone, I came across a helpful resource on implementing multiple checkboxes filters in AngularJS: angular js multiple checkbox with custom filters I am facing a similar issue but with a multilevel JSON structure. Here is an example of what I am deal ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...

combine ngClass properties if substitution is true

My directive includes replace: true in the definition. <my-custom-tag> </my-custom-tag> This is the template for the directive: <div data-ng-class="{'class1': condition1, 'class2': condition2}"> </div> When u ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

What is the reason for the base class constructor not being able to access the property values of the derived class

Recently, I came across this scenario in my code: class Base { // Default value myColor = 'blue'; constructor() { console.log(this.myColor); } } class Derived extends Base { myColor = 'red'; } // Prints ...

Stack two divs together

It may seem silly, but I just can't get it to work. I'm attempting to enclose two divs with different classes in another div, but my current code is automatically closing the divs. There are multiple sets of divs with classes .panel-heading and ...

What is the best approach to setting up dynamic Vue routing?

I am working on implementing dynamic routing for the website that relies on changes in agreements. Here is the path tree I have set up: const routes = [ { path: "/", redirect: "/home", component: DefaultLayou ...

Tips for managing React state when dealing with multiple axios callbacks that modify an array's state

I am currently working on a React component that allows users to upload images. In this scenario, I aim to upload 3 images. After each file is uploaded, I want to append it to the list of uploaded files. Issue: The setter method in useState is asynchronou ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...