简体   繁体   中英

Use object from Node.js / Express backend in frontend JS

Noob in programming here, my question is probably fairly stupid but I've been spending a lot of time searching for a solution to no avail.

I'm coding a prototype for a simple web app. Back end uses Node.js, Express and MongoDB. I use twig to render the pages to the client. And I need to use some frontend JS.

Here is my route:

router.get("/game/:id", objectsController.showObjectGame)

Here is the controller:

exports.showObjectGame = (req, res) => {
objectModel.findById(req.params.id)
.exec()
.then(object => {
    res.render("objectGame.html.twig", {object: object})
})
.catch(error => {
    console.log(error);
})}

Then I'm able to render a page with a given object properties:

<h2>Title1</h2>
    <div id="property1">{{object.property1}}</div>

<h2>Title2</h2>
    <div id="property2">{{object.property2}}</div>
<h2>Title3</h2>
    <div id="property3"><img src="/images/{{object.property3}}"></div>

On this page, I import a JS file:

<script src="/javascript/objectGame.js"></script>

My issue is that I need to pass the object to a variable in objectGame.js, in order to execute the frontend script. For the life of me, I can't figure how to do it.

Hope this makes sense.

Thanks in advance !

Here's what I think could be useful. First we have to restructure code in objectGame.js . For this we can use IIFE pattern.

Here's how objectGame.js code will look like

 const objectGame = (function() {
  //varible initializations
  let somevar = null;
  
  function _init(objectFromServer) {
    somevar = objectFromServer;
   //other initilization code
  }

  //other functions

  return {
    init: _init,
    //other methods can be added
  }
})();

After importing objectGame.js objectGame function defined above will be available in global space and can be used like this.

<script src="/javascript/objectGame.js"></script>
<script>
  objectGame.init({{someObjectFromServer}});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM