简体   繁体   English

如何将js中的变量从服务器端传递到nodejs中的客户端

[英]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.我正在使用 pubnub 和 nodejs 为学校构建一个类似 skribble.io 的项目。 base code from Guesswordpubnub .来自Guesswordpubnub的基本代码。 In pubnub we need to provide a channel for lobby like connection.在 pubnub 中,我们需要为大厅之类的连接提供通道。 I implemented the pubnub things in client side scripts and my code:我在客户端脚本和我的代码中实现了 pubnub 的东西:

in serverside "routename.js":在服务器端“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我如何将lobbyName从服务器传递到客户端lobby

I don't know what to do.If it is stupid question, pardon我不知道该怎么办。如果这是愚蠢的问题,请原谅

I am a beginner.我是初学者。 only familiar with vanilla js Thanks只熟悉vanilla js 谢谢

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:在 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>在视图playground上,我正在使用外部 js 文件,所以脚本 src 标记之前我应该提到<script>var lobby ={{lobbyName}}</script>

so the playground.hbs:所以游乐场.hbs:

<script>var lobby ={{lobbyName}}</script>
<script src="/javascripts/lobby.js" ></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将JS对象从服务器端传递到NodeJS中的客户端 - How can I pass JS objects from the server-side to the clientside in NodeJS 如何将变量从服务器端返回到客户端脚本? - How do I return variables from serverside back to the clientside script? 如何在ClientSide中调用提取的方法以从ServerSide接收数组? - How to call fetched method in ClientSide to receive an array from ServerSide? 如何从类文件(服务器端)向.aspx文件(客户端)发出请求? - How to make request from Class files(serverside) to .aspx file(clientside)? 要用js迭代html svg服务器端或客户端? - To iterate a html svg serverside or clientside with js? 如何从NodeJS的客户端获取上传的文件? - How to get uploaded file from clientside in NodeJS? 如何将来自 NodeJS API 的数据作为变量传递给 static JS 文件? - How to pass data from NodeJS API as a variable to a static JS file? 如何在clientSide和ServerSide中使用selectedIndexChanged下拉列表 - How use selectedIndexChanged dropdownlist in clientSide and ServerSide 如何维护服务器端验证和客户端验证 - How to maintain serverside validation and clientside validation ServerSide(PHP)与ClientSide(JS)的权衡关系 - ServerSide(PHP) vs. ClientSide(JS) running trade off
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM