Zernst
Zernst

Reputation: 325

Pass Data From Node/Express to Front-End Javascript

I am unsure how this would work exactly, and I am unable to find my answer from searching for it. I am working with a node and express server, and have been passing data to my front end ejs without issues. Now, I am trying to implement charts.js in my front-end, and that requires the data to be in a front-end javascript file. I know that to pass data to my ejs file, I use something like this:

res.render("dashboard", {data: data});

and to display the data in the ejs file, I use

<%= data %> 

Now, what I would like to do, is basically the same thing, but instead of passing the data into an ejs file, I want to pass it into a javascript file, while still displaying the ejs file. Right now, I can't seem to figure out how I go from having my data in the express server, and returning it into a front-end javascript file. The flow I am looking for would be something like this:

In node:

data = []:
res.render("dashboard", {data: data});

and then the ejs file is rendered and data is passed into the front-end javascript file that is being used within the ejs file:

let data = <%= (data array passed from the node server here) %>

Of course, this is not the correct way to write the code, but this is the basic logic I am trying to implement.

I am sure this is something simple, but I can't seem to find the answer within my context here. Are there any resources where I can learn to do what I am trying to do? Thanks.

Upvotes: 1

Views: 1919

Answers (1)

Quentin
Quentin

Reputation: 944213

You can't respond to a single request with both an HTML document and a seperate JavaScript file.

So you need to either:

  • Store the data somewhere and, in a separate endpoint, serve up some generated JavaScript and have a mechanism which identifies which data to serve up when the request is made. (NB: This is stupidly complex. Don't do it.)
  • Generate the JavaScript inline in the HTML document inside a <script> element. (You'll need to properly escape the data as JS to make sure you aren't subject to XSS).
  • Output the data into the HTML document (e.g. with data-* attributes or <meta> elements) and read it with static JavaScript.
  • Again, using a seperate endpoint: Serve up JSON with the data in it and read that with Ajax from a static JS file. (Again, you'll need a way to determine which data to send for that particular request).

Upvotes: 2

Related Questions