我正在使用Node.js,并且遇到与客户端进行通信的问题。
我定义了Express:
var express = require("express"); var app = express();`当我尝试在请求页面时向客户端传递参数时,该变量不包含任何数据,例如:
app.get("/", function(req, res){ res.render("index", { name: "example" }); });在索引页上,当我使用控制台打印变量( name )时,它返回"" 。
更多信息: http : //expressjs.com/api.html#app.render
我错过了什么或做错了什么?
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?
最满意答案
发送给渲染函数的变量name仅在呈现页面时才可用,发送给客户端后,该页面无法访问。 您必须在渲染阶段的视图中使用它。
由于您使用的是把手,因此可以像这样在页面中显示它,例如:
<h1>{{ name }}</h1>如果您想在JavaScript中使用这些数据,请在script标记中使用它:
<script> var name = "{{ name }}"; console.log(name); </script>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>更多推荐
发布评论