简体   繁体   中英

How to pass variable in js from serverside to clientside in nodejs

I am building a project like skribble.io for school using pubnub and nodejs. base code from Guesswordpubnub . In pubnub we need to provide a channel for lobby like connection. I implemented the pubnub things in client side scripts and my code:

in serverside "routename.js":

router.get("/:link", function (req, res, next) {
  res.render("playground");
  var lobbyName = req.params.link;
});

and now in client side i am simply prompting for a name

  let lobby = prompt("Enter name of lobby");

how can i pass the lobbyName from server to client side lobby

I don't know what to do.If it is stupid question, pardon

I am a beginner. only familiar with vanilla js Thanks

You can pass variables directly to your view by doing something like this:

router.get("/:link", function (req, res, next) {
  let lobbyName = req.params.link;
  res.render("playground", {lobbyName: lobbyName});
});

In routername.js:

router.get("/:link", function (req, res, next) {
  let lobbyName = req.params.link;
  res.render("playground", {lobbyName: lobbyName});
});

in the view playground i am using external js file so before the script src tag i should mention <script>var lobby ={{lobbyName}}</script>

so the playground.hbs:

<script>var lobby ={{lobbyName}}</script>
<script src="/javascripts/lobby.js" ></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