将变量从Node.js发送到与HTML一起呈现的JavaScript文件。

huangapple go评论72阅读模式
英文:

Send variable from nodejs into js file that has rendered alongside html

问题

I'm pretty new to nodejs.

如何在我的app.js中传递一个变量,以便与我的html一起呈现的app.js文件中使用?这是否可能?

例如,如下所示,尝试将myvar的值发送到/public/js/app.js文件。我知道我可以将其设置为通过ejs文件内联脚本,只是在寻找更好的替代方法。

app.js

app.use(express.static("public"));

//

app.get("/my-page", function (req, res) {

    var myvar = "Hello"
 
    res.render("my-page.ejs");
  }
});

//

/views/my-page.ejs

<h1>Hello World</h1>

<script type="text/javascript" src="./js/app.js"></script>
/public/js/app.js

var myvar2 = myvar + " World!"

console.log(myvar2)

谢谢!

英文:

I'm pretty new to nodejs.

How do I pass a variable in my app.js, to the app.js file that renders together with my html? Is this possible?

For example, as below, trying to send the value of myvar to the /public/js/app.js file. I am aware that I could set it up as an inline script through the ejs file, just was looking for better alternatives to that.

app.js

app.use(express.static(&quot;public&quot;));

//

app.get(&quot;/my-page&quot;, function (req, res) {

    var myvar = &quot;Hello&quot;
 
    res.render(&quot;my-page.ejs&quot;);
  }
});

//

/views/my-page.ejs

&lt;h1&gt;Hello World&lt;/h1&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;./js/app.js&quot;&gt;&lt;/script&gt;
/public/js/app.js

var myvar2 = myvar + &quot; World!&quot;

console.log(myvar2)

Thanks!

答案1

得分: 2

由于您正在使用Express作为框架,您可以使用"Express.js res.locals Property"。

app.js

app.use(express.static("public"));

app.get("/my-page", function (req, res) {

  var myvar = "Hello";

  res.locals.myvar = myvar; //您可以在这里设置变量

  res.render("my-page.ejs");
});

然后在HTML中,您可以通过以下方式访问:

/public/js/app.js

var myvar2 = window.myvar + " World!"; //您可以通过window对象访问

console.log(myvar2);

然后,由于您正在使用EJS模板表达式,您可以通过以下方式访问它:

<h1><%= myvar %></h1>

要获取更多信息,您可以查看Express页面

其他从HTML访问变量的方式可以是:

<div id="myvar-container"></div>

<script>
  var myVarContainer = document.getElementById("myvar");

  myVarContainer.innerHTML = '<%= myvar %>'; // 使用变量值设置innerHTML
</script>

但总的来说,如果涉及到更复杂的情况,我建议您使用一些库或框架(如React或Angular)进行数据绑定。

app.locals对象包含在应用程序内部作为本地变量可访问的属性,并且可以在使用res.render呈现的模板中使用。为了更安全地呈现,您可以使用以下方式:

app.get("/my-page", function (req, res) {
  var myvar = "Hello";
  res.render("my-page", { myvar: myvar }); // 通过res的render方法发送变量。
});

要获取更多信息,请查阅我之前提供的官方文档链接。

英文:

Since you are using Express as a framework you can use "Express.js res.locals Property".

app.js
    
app.use(express.static(&quot;public&quot;));
    
app.get(&quot;/my-page&quot;, function (req, res) {
    
  var myvar = &quot;Hello&quot;;

  res.locals.myvar = myvar; //You can set up the variable here

  res.render(&quot;my-page.ejs&quot;);
});

And then in the html you can access through:

/public/js/app.js

var myvar2 = window.myvar + &quot; World!&quot;; // You can access through window object

console.log(myvar2);

Then since you are using EJS template expression you can access it through:

&lt;h1&gt;&lt;%= myvar %&gt;&lt;/h1&gt;

For more info you can look at express page

Some other way to access to the variable from HTML would be:

<div id="myvar-container"></div>

&lt;script&gt;
  var myVarContainer = document.getElementById(&quot;myvar&quot;);

  myVarContainer.innerHTML = &#39;&lt;%= myvar %&gt;&#39;; // Set the innerHTML with the variable value
&lt;/script&gt;

But overall If its something more complex I would suggest you to use some library or framework (React or Angular) for data binding.

The app.locals object contains properties that are accessible as local variables within the application and can be used in templates rendered with res.render. For safer lets say way of rendering you can use:

app.get(&quot;/my-page&quot;, function (req, res) {
  var myvar = &quot;Hello&quot;;
  res.render(&quot;my-page&quot;, { myvar: myvar }); // send the variable through render method from res.
});

For more information check the official documentation that I've linked previously.

答案2

得分: 1

JSON 来拯救。我们发送一个带有正确值的 &lt;script&gt; 标签。诀窍在于首先将模板文件呈现为 HTML,但 Express 提供了一个回调函数。

// 在 Node.js 中:

function my_render(res, template, data, obj) {

  res.render(template, data, function(err, html) {
    if (err) {
      throw new Error("something")
    }

    html += "\n&lt;scr" + "ipt&gt;var my_var = " + JSON.stringify(obj) + ";&lt;/scr" + "ipt&gt;";

    res.send(html);
  });

}

// 在客户端:
// my_var = 服务器上的对象

请注意,我已经将 &lt;script&gt; 标签中的特殊字符转义为正常文本。

英文:

JSON to the rescue. We send a &lt;script&gt; tag with the proper values. The trick is rendering the template file into html first, but express offers a callback for that.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// in node.js:

function my_render(res, template, data, obj) {

  res.render(template, data, function(err, html) {
    if (err) {
      throw new Error(&quot;something&quot;)
    }

    html += &quot;\n&lt;scr&quot; + &quot;ipt&gt;var my_var = &quot; + JSON.stringify(obj) + &quot;;&lt;/scr&quot; + &quot;ipt&gt;&quot;;

    res.send(html);
  });

}

// in client:
// my_var = object that was on server

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月3日 19:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/74993004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定