Node.js通过快速渲染将参数传递给客户端(Node.js passing parameters to client via express render)

编程入门 行业动态 更新时间:2024-10-28 02:26:49
Node.js通过快速渲染将参数传递给客户端(Node.js passing parameters to client via express render)

我正在使用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>

更多推荐

本文发布于:2023-08-07 13:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   参数   快速   js   Node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!