0

I have the below codes, I am trying to access data sent from my backend server in my frontend js. How can I do that?

Express

...
app.get("/", (req, res) => {
  res.render("home", {data} );
});
...

home.ejs

...
<script src="frontend.js"></script>
...

frontend.js

var data = <%=data%>; // this didnt work...
chongzixin
  • 1,951
  • 4
  • 28
  • 55
  • take a look at this [accessing passed ejs variable in javascript file](https://stackoverflow.com/questions/46539106/accessing-passed-ejs-variable-in-javascript-file) – Yousaf Jan 30 '20 at 14:00

1 Answers1

0

You could directly inject the data variable into javascript on the page.

<% if (data) { %>
     <h2>I have data</h2>
     <script>
        var data = <%= data %>            
     </script>
<% } %>

Another option might be to make an AJAX call back to the server once the page has already loaded, return the data

shashi kumar
  • 362
  • 2
  • 9
  • you may refer this https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser – shashi kumar Jan 30 '20 at 14:04