Javascript Node.js 通过快速渲染将参数传递给客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29328028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js passing parameters to client via express render
提问by g571792
I'm using Node.js and I'm having issues communicating with a client.
我正在使用 Node.js,但在与客户端通信时遇到问题。
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 "".
在索引页上,当我使用控制台打印变量 ( name) 时,它返回"".
More info: http://expressjs.com/api.html#app.render
更多信息:http: //expressjs.com/api.html#app.render
Am I missing something or doing something wrong?
我是否遗漏了什么或做错了什么?
回答by victorkohl
The variable nameyou 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.
name您发送给渲染函数的变量仅在渲染页面时可用,发送给客户端后,将无法访问。您必须在渲染阶段的视图中使用它。
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 scripttag:
如果要在 javascript 中使用此数据,请在script标签中使用它:
<script>
var name = "{{ name }}";
console.log(name);
</script>
回答by Jean-Marc S.
You are basically telling express to render your index page and providing a value for the namevariable, but that doesn't necessarily make the namevar available in your client side javascript. You need to edit your index template to display the namevariable in the page.
The syntax varies depending on the templating engine you are using (jade, ejs, dustjs).
您基本上是在告诉 express 呈现您的索引页面并为name变量提供一个值,但这并不一定使namevar 在您的客户端 javascript 中可用。您需要编辑索引模板以name在页面中显示变量。语法因您使用的模板引擎(jade、ejs、dustjs)而异。
Another solution is to use an ajax call in your client page's javascript and use res.jsonon the server instead to send the data. Then you can evaluate namein the console. Ex using jquery:
另一种解决方案是在客户端页面的 javascript 中使用 ajax 调用,并res.json在服务器上使用来发送数据。然后您可以name在控制台中进行评估。例如使用 jquery:
index.html:
索引.html:
$.get( "/getvar", function( data ) {
name = data.name;
});
server.js:
服务器.js:
app.get("/getvar", function(req, res){
res.json({ name: "example" });
});
回答by marsh
If you want to get parameters on the clientside via javascript, you should do template like this <script>var data = data</script>, otherwise variables aren't available
如果你想通过javascript在客户端获取参数,你应该像这样做模板<script>var data = data</script>,否则变量不可用
If you use Jade, it will be something like this:
如果您使用 Jade,它将是这样的:
script(type='text/javascript').
var name = !{name}
回答by Rahamath
Passing data list from node js to html
将数据列表从节点 js 传递到 html
server.js
服务器.js
var http = require('http');
var express = require('express');
var sqlite3 = require('sqlite3').verbose();
var bodyParser = require('body-parser');
var path = require("path");
console.log('Server running at http://127.0.0.1:8081/');
var __dirname = "D:/html-files";
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var engine = require('consolidate');
app.engine('html', engine.mustache);
app.use(express.static('./'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
});
app.post('/get-user-list', urlencodedParser, function (req, res) {
let db = new sqlite3.Database('user.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the user database.');
console.log("ID" + "\t" + "NAME" + "\t" + "EMAIL");
});
db.serialize(() => {
var dataList = "";
db.each('SELECT id, name, email FROM USER ', (err, row) => {
if (err) {
console.error(err.message);
}
if(dataList != "")
dataList = dataList + ',';
dataList = dataList + '{"id":"' + row.ID + '","name":"' + row.NAME + '","email":"' + row.EMAIL + '"}';
console.log("dataList : " + dataList);
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
response = {'username':dataList};
aFunction(res, dataList);
});
});
});
var aFunction = function(res, dataList) {
console.log('return to page.');
console.log("dataList : " + dataList);
res.render(__dirname + "/list-all-users.html", response);
};
app.listen(8081, '127.0.0.1')

