EJS 使用提取的 json 数据与 d3 图表



*新表达。

我有index.ejsscript.js.

我的脚本可以从 api 获取一些 JSON 数据。

const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
})
.catch(err => {
})

我将如何使用这些返回的 JSON 数据在带有 d3 的索引页中创建图表。

我已经四处搜索,但仍然感到困惑。任何建议都会超级有帮助!谢谢。

因此,正如评论中所讨论的,问题是有一个在nodejs的快速框架中返回的服务器

所以在快递代码中需要调用一个 api 并获取数据,一旦我们拿到数据就需要将其发送到前端。

因此,为了将数据返回到前端,我们可以使用 res.send of express

const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
res.send(data)
})
.catch(err => {
})

在前端,我们需要访问这个 api,如下所示

const getData = async () => {
try {
const response = await fetch(url) // server url (express js route) example http://localhost:6000/api/getChartData
if(response.ok){
const  body = await response.json()
console.log(body)
// once you get the data you can create d3 chart
return
}
const customError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error) 
// put the error in  a variable  and display on the ui so the user know some error happened
}
}

最新更新