Reputation: 325
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
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:
<script>
element. (You'll need to properly escape the data as JS to make sure you aren't subject to XSS).data-*
attributes or <meta>
elements) and read it with static JavaScript.Upvotes: 2