简体   繁体   中英

EJS using fetched json data with d3 chart

*New to express.

I have index.ejs and script.js .

My script fetches some JSON data from an api just fine.

const fetch = require("node-fetch");
const url = '...'

fetch (url)
    .then(response => {
        return response.json()
    })
    .then(data =>{
    console.log(data)
    })
    .catch(err => {
    })

How would I go about using this returned JSON data to create a chart in my index page with d3.

I have searched around but am still confused. Any advice would be super helpful! Thanks.

So as discussed in the comments, the problem was having a server which is return in express framework of nodejs

So in express code need to call an api and get data, once we get the data we need to send it to the front end.

So for returning data to front end we can use 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 => {
    })

And in the front end we need to access this api as shown below

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM