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

what is the most effective method for integrating Vue with Express?

1: I have successfully installed expressjs on my system. 2: Following that, I used npm to install the vue framework by running 'npm install vue --save'. 3: Additionally, I utilized handlebars as the template-engine for expressjs. In my index.hbs ...

Issue with uncaught exceptions in promise rejection test

I am experiencing an issue with the following code: function foo(){ bar().catch(function(){ //do stuff } } function bar(){ return promiseReturner().then( function(result){ if(_.isEmpty(result)){ throw "Result is empty"; ...

Can you identify the nature of the argument(s) used in a styled-component?

Utilizing typescript and react in this scenario. Fetching my variable const style = 'display: inline-block;' Constructing a simple component export const GitHubIcon = () => <i className="fa-brands fa-github"></i> Enh ...

Transfer the parameter from ajax function to the aspx.cs file

I've written some code using HTML, JS, and AJAX, but it's not functioning as expected. <script type="text/javascript"> function DeleteSelectedRecord(id) { alert(id); $.ajax({ type: "POST", ...

Try enabling automatic status bar filling in Onsen UI when working with AngularJS

Completely new to AngularJS, I am trying to understand how to use ons.enableAutoStatusBarFill(); in order to prevent my menus from overlapping the status bar. This is how I have set up my controller: var mod = ons.bootstrap('app', ['onsen& ...

What is the necessary step to configure the "basedir" option for Jade in an Express application? (This option is essential for utilizing "extends" with absolute paths)

As I work my way through the peepcode nodejs video and try to recreate the app using the latest express/node versions, I've encountered a minor issue. Here is the current file structure: site - apps - - authentication - - - views - - - - login.j ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

Unusual CSS rendering hiccup

Using jQuery, I am manipulating the display of an <a> element. Depending on certain keypress events, it adds or removes a class from an <input> element (which controls the display) that is related as a sibling to the mentioned <a>. The i ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Can you explain the distinction between incorporating the Express GET method and HTTPS GET method in the provided code snippet?

const express = require("express"); const app = express(); const https = require("https"); app.get("/", function (req, res){ var url = "https://example.com"; https.get(url, function(response){ ...

Restricted Submission Request

Currently, I am developing a form where each time a user clicks on an option, a post request is sent to the server to update the database. However, my server can only accept up to 6 post requests at a time. If more than 6 requests are made, the additional ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

Scan for every header tag present and verify the existence of an id attribute within each tag. If the id attribute is absent, insert

Looking to locate all header tags within the content and verify if each tag has an id attribute. If not, then jQuery should be used to add the id attribute. Here is the code snippet: var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); $.each( ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...

Establishing communication between a master process and worker processes in Node.js: A guide to verifying bidirectional communication

After coming across this particular script from the node documentation, I tried to implement it for sending messages between Master and worker processes using cluster. However, upon running the script, I encountered an issue where I could not verify the me ...

Exploring and verifying data within an array in ReactJS

In ReactJS, there is a variable that contains the result of validation as an array: console.log(this.state.check); // [account: false, name: true, email: true] Here's what needs to be done: If all values in the array are true, return true. If one or ...

Running tests to check for next(err) functionality using supertest and Express JS

When using Express in a route or middleware, you can halt the callback chain by calling next(err) with any object as err. This feature is well-documented and simple to understand. However, I encountered an issue when testing this behavior with SuperTest. ...