Utilizing EJS to display dynamic data from a JSON file in a visually appealing D

*Excited about learning express!

Currently, I have two files - index.ejs and script.js.

The script I've written successfully fetches JSON data from an api.

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

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

I'm wondering how to utilize the fetched JSON data to create a chart using d3 on my index page.

Although I've done some research, I'm still feeling uncertain. Any guidance would be greatly appreciated! Thank you.

Answer №1

After some discussion in the comments, it was determined that the issue stemmed from using a server implemented in the Express framework of Node.js.

In an Express application, to retrieve data from an API and send it to the frontend, you can utilize the res.send method.

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

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

To access this API on the frontend, follow the example below:

const getData = async () => {
  try {
    const response = await fetch(url) // Example: http://localhost:6000/api/getChartData
    if(response.ok){
      const body = await response.json()
      console.log(body)
      // Perform actions like creating a D3 chart once data is received
      return
    }
    const customError = {
      message: 'Something went wrong'
    }
    throw customError
  } catch(error){
    console.log(error)
    // Store the error in a variable and display it on the UI to inform the user of any errors
  }
}

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

onload function prevents further URL redirection

After submitting the form "View this product," a function is triggered to retrieve the product id from the form data. Although I can successfully obtain the form_data, the page does not redirect as expected. I suspect that my function may not have been pr ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

Combining various queries into a single JSON object compared to executing multiple queries individually

I have a situation where I need to execute multiple unrelated queries in order to generate a page. Up until now, I have been converting each query result into a JSON object before aggregating them together with a structure like this: SELECT (SELECT array ...

Obtaining the value of an item in an unordered list

Hi everyone, I have been trying to extract the value of <li> elements that display images horizontally. Below is the HTML code I am working with: <div id="layoutInnerOptions"> <ul id="navigationItemsContainer" class="layouts_list"> <l ...

What is the best way to declare a global TypeScript variable in a definition file to make it accessible for import?

My issue revolves around an external JS library that contains a global parameter: function Thing() { ... } ... var thing = new Thing(); I have a TypeScript definition file named thing.d.ts with the following content: declare var thing: ThingStatic; ex ...

How to iterate dynamically over arrays using JavaScript

I am working on a JavaScript project where I need to create a graph with 25 different data points. While my current JavaScript method is effective, I am facing an issue - I have multiple arrays and I am looking for a solution that allows me to use a for lo ...

Guidance on exporting an Excel file from an HTML table, excluding the final row, using JavaScript

I'm able to export an Excel file from an HTML table, but I'm facing an issue where the last row (tr) meant for pagination on the screen is also being included in the exported result. How can I exclude this row from showing up in the Excel file? ...

React and React Native not synchronizing with authentication context

It seems like there is an issue with the AuthContext not updating properly. Despite logging at various points, the user is still not being set. Here's a glimpse of the code in question: App.tsx export default function App() { const { user, setUser ...

New Relic identifies mysterious delays caused by MongoDB's findOne method

After setting up newrelic to pinpoint the bottlenecks in my app, I discovered a major issue that has left me stumped. The source of most delays seems to be mongoDB user.findOne, but the biggest challenge is locating where in the code this delay is occurri ...

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

Eliminating certain buttons within Ember-leaflet-draw

Is there a way to remove specific buttons from the UI in my Ember application that are used for drawing lines, circles, and polygons? I am currently using Leaflet Draw in my project. Here is a snippet of my template.hbs: {{#leaflet-map onLoad=(action &apo ...

Using async/await in React.js to handle API calls results in a

It's puzzling to me why calling the API directly using async await in useEffect() results in getting data immediately when the component mounts, but when I call getLevels() from selectApi.js, it returns undefined. Take a look at the code snippet below ...

How can I effectively separate the impact of Next.js onChange from my onClick function?

The buttons in my code are not functioning properly unless I remove the onChange. Adding () to my functions inside onClick causes them to run on every keystroke. How can I resolve this issue? In order to post my question, I need to include some dummy text. ...

The functionality of Angular Views is experiencing issues

I'm confused as to why the JavaScript isn't functioning properly. Whenever I click on the links, the views fail to load. <html ng-app> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/a ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

Avoid reloading the page when the form is submitted using form.trigger('submit') command

My current code functions properly when the user clicks on the form's submit button: // load dashboards when filter form is submitted $('div.active form.filter-form').submit(function (e) { // get subm ...

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...

JQuery mishandles its left positioning

Here's the code snippet I've been working with: $(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({ top: $(this).offset().top - 57, left: -$(this).widt ...

Mongoose failing to retrieve complete data set

In the setup of my Model, I have defined it as follows: var Post = mongoose.Schema({ "_uid": String, "post_title": String, "post_content": String, "post_date": Date, "user": String, "slug": String, "attached_medi ...