【发布时间】:2020-09-09 00:25:11
【问题描述】:
我有一个带有 API 的 .NET Core 服务器,我试图通过 AmCharts“默认”加载方法请求数据。
服务器端端点如下所示:
[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" });
}
}
}
我知道服务器部分可以正常工作,因为我可以通过如下所示的 JS Fetch 请求请求数据,并且工作正常。
let response = await fetch("api/stocks/getstockintraday1min/tsla", {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
}
})
但是,当我尝试通过 AmCharts 以您应该的方式做同样的事情时,我在 FireFox 控制台中收到一个 401 Unauthorized Request,如下所示:
XHR GET https://localhost:44397/api/stocks/getstockintraday1min/tsla [HTTP/2 401 Unauthorized 8ms]
就像 AmCharts 文档建议的那样(https://www.amcharts.com/docs/v4/reference/datasource/#Properties 向下滚动到“requestOptions”),我尝试使用我的不记名授权令牌设置一个请求标头,但它拒绝工作。我尝试了以下方法:
// 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()
如果我只使用“授权”,上面显示的内容将不起作用:Bearer ${authToken}
我也试过了:
// 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()
上面只有 Authorization: Bearer 行,或者没有围绕 JSON 对象的 [] 也不起作用。
搜索 YouTube 也一无所获,因此,如果有人对我遗漏的内容有任何线索,将不胜感激。
【问题讨论】:
标签: javascript authentication charts amcharts amcharts4