Node.js passing parameters to client via express render

Hey Replit community!
I’m working on a Node.js project and wanted to know how to retrieve parameters of a res.render() function on the server side on the JS file on the client side. For example:


app.get('/:id', function(req, res) {
      // some code
      var dt = {key: 'value'}
      res.render('pages/account', {
          data: dt

client JS:

     // code to retrieving the data (idk how)
     document.getElementById("foo").innerHTML = JSON.stringify(retrieved_data);

I’ve tried some solutions from Stackoverflow (here) but they all didn’t work for me.
Also, I tried to retrieve the data directly from .ejs file via <p id="foo"><%= JSON.stringify(data) %></p> and it worked just fine. The problem is, I want to do some preparations to the data before displaying it in browser and so I need to be able to get the data in client JS.

How can do it?

What if you place the ejs like so?

<p id="foo" style="display: none;"><%= JSON.stringify(data) %></p>

This way, you can still pull from an element, and it’s not displayed to the end user.

And if you need to get the data back as an object for your JS code:

data = JSON.parse(document.getElementById("foo").innerHTML)

Wow, I thought the solution will be much more complicated… Thanks for help @Firepup650 !

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.