0

I'm running a simple Node.js server, and I have a function defined that I want to load as in inline script (in an HTML file/template) and then send that template to the client. I guess this is essentially basic Server Side Rendering (SSR)?

I'm not sure how to go about this though... I though it would be really simple but am having some trouble. I've tried templating with EJS but have not have any luck so far. But I'm pretty new to EJS and server side templating some I may be missing something really simple.

This is the type of code/template I'm trying, where initUser is the function I want inline:

app.get('/*', (req, res) => {
  res.render('test-template', {
    initUser: initUser,
  });
});
  <body>
    <h1>An EJS template</h1>
    <script>
      ('<%= initUser %>');
    </script>
  </body>

But then in the browser after I hit the end point and look in the elements tab of dev tools this is what I see:

<script>
  ('[object Object]')
</script>

Can anyone point me in the right direction? I feel like this should be relativity simple and I'm probably missing something obvious but I would really appreciate some help.

jerfp
  • 417
  • 5
  • 13
  • Try changing to: `initUser: JSON.stringify(initUser)` – testing_22 Mar 11 '21 at 16:52
  • Then an empty object ```{}``` is inside the script tag – jerfp Mar 11 '21 at 16:55
  • Have you checked if the response has data – testing_22 Mar 11 '21 at 17:05
  • Not sure if I understand what you mean... I want the entire function loaded inline, not just a return value. The function uses things like cookies and utm params in its logic, so I need the whole thing to run on a client. – jerfp Mar 11 '21 at 17:09
  • Check if this answers your question: https://stackoverflow.com/questions/13788314/express-and-ejs-to-render-a-json – testing_22 Mar 11 '21 at 17:10
  • That sounded promising but I still get an empty object when I try ```<%- JSON.stringify(initUser) %>``` in the template :( – jerfp Mar 11 '21 at 17:25
  • So as I tried to explain, the problem must be in your response: returning { } (that's why it is rendered) – testing_22 Mar 11 '21 at 17:33
  • Could you explain what you mean? And just to be clear on what I'm looking for, I want the actual function passed to the client, I don't want to execute this function on the server. – jerfp Mar 11 '21 at 17:53

0 Answers0