0

I am trying to make an express template that displays a post based on the URL / params. Similar to what we have on StackOverflow (I have topic instead of questions + id): https://stackoverflow.com/questions/111111/ and I have: localhost:8003/act/random/111111/

authController.act requests and returns post data from MySQL. This is my route:

router.get('/act/:topic/:id/:title?', authController.isLoggedIn, (req, res, next) => {

  const promise = authController.act(req.params.topic, req.params.id);
  promise.then((results) => {
    res.render('act', {
      message1: 'some message', results: results
    });
  });

});

And than I want to use it in my HTML/EJS file:

<body onload="init();loadAct(results)">

My results get successfully passed to the EJS file and can be used like this <%- results %> as suggested by Kapil Sharma. Now I need to figure out why it won't work in JS.

Uncaught ReferenceError: results is not defined
    onload http://localhost:8003/act/random/127/:1

Edit: This seems to solve my problem. Quentin also proposed a second solution below if this doesn't help.

<body onload="init();loadAct(JSON.parse('<%= JSON.stringify(results) %>'));" >
Nik
  • 96
  • 7
  • 1
    res.json() will not be able to render HTML. Did you try printing in your EJS <% console.log(results) %> or printing it like

    <%- results %>

    – Kapil Sharma Aug 23 '21 at 10:11
  • Thanks for the suggestion. It does actually work like that. It seems that I have a problem passing from EJS to JS in the onload. – Nik Aug 23 '21 at 11:22
  • The JavaScript program that *runs on the server via the EJS template processor* and the completely different JavaScript program that *runs in the browser via the `onload` attribute* are completely different JavaScript programs. They don't share variables. – Quentin Aug 23 '21 at 11:29
  • @Nik You must get the value inside the – Kapil Sharma Aug 23 '21 at 11:40
  • @Quentin Ty for the input. I also found that this works: `loadAct(JSON.parse('<%= JSON.stringify(results) %>'));` – Nik Aug 23 '21 at 11:42

0 Answers0