Node.js通过express渲染将参数传递给客户端 [英] Node.js passing parameters to client via express render
问题描述
我定义Express:
var express = require(express);
var app = express();`
当我尝试将参数传递给客户端在请求页面时,变量不保存数据,例如:
app.get(/,function(req, res){
res.render(index,{name:example});
});
在索引页上,当我使用控制台打印变量(名称
)它返回。
更多信息: http://expressjs.com/api.html#app.render
我缺少某些东西或做错了什么?
变量 name
你发送到render函数只有在渲染页面时才可用,在发送到客户端之后,它是不可访问的。您必须在渲染阶段的视图中使用它。
由于您正在使用句柄,因此您可以在此页面上显示它,例如:
< h1> {{name}}< / h1>
如果要在javascript中使用此数据,请在脚本
标签:
< script>
var name ={{name}};
console.log(name);
< / script>
I'm using Node.js and I'm having issues communicating with a client.
I define Express:
var express = require("express");
var app = express();`
When I try and pass a parameter to the client upon requesting a page the variable holds no data, for example:
app.get("/", function(req, res){
res.render("index", { name: "example" });
});
On the index page, when I use the console to print the variable (name
)it returns ""
.
More info: http://expressjs.com/api.html#app.render
Am I missing something or doing something wrong?
The variable name
you sent to the render function is only available while rendering the page, after it is sent to the client, it is not accessible. You have to use it in your view on the rendering stage.
Since you are using handlebars, you can display it in your page like this, for instance:
<h1>{{ name }}</h1>
If you want to use this data in a javascript, use it inside a script
tag:
<script>
var name = "{{ name }}";
console.log(name);
</script>
这篇关于Node.js通过express渲染将参数传递给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!