HTML客户端和Node.js服务器之间的variables

我只想将HTML页面中的variables传递给节点js,并对数据执行一些计算,并使用ejs将其返回到HTML。安装ejs之后:

npm install ejs 

我试图通过值50“HTML页面”这个variables温度:

 <html> <head> </head> <body> My temperature: <%= temp=50 %> Temp + 10 : <%= total %> </body> </html> 

和我的nodejs server.js:

 var http = require('http'); var ejs = require('ejs'); var fs = require('fs'); http.createServer(function(req,res) { res.writeHead(200, {'Content-Type': 'text/html'}); //since we are in a request handler function //we're using readFile instead of readFileSync fs.readFile('index.html', 'utf-8', function(err, content) { if (err) { res.end('error occurred'); return; } var temp; //here you assign temp variable with needed value var total = temp+10; var renderedHtml = ejs.render(content, {temp: temp, total:total}); //get redered HTML code res.end(renderedHtml); }); }).listen(8080); 

任何帮助,将不胜感激预先感谢。

在你的服务器文件中,temp的值是未定义的。 总共=未定义+ 10 =未定义。 因此你的variables在服务器文件中是未定义的。 尝试这样做(在服务器文件中): var temp = 0 var total = 0

在html文件中My temperature: <%= temp = 50 %> Temp + 10 : <%= total = temp + 10 %>现在,它应该显示正确的值,即50和60。

你不需要这个fs要求。

所有你需要做的是:

 var express = require('express'); var app = express(); var path = require('path'); //Use the path to tell where find the .ejs files // view engine setup app.set('views', path.join(__dirname, 'views')); // here the .ejs files is in views folders app.set('view engine', 'ejs'); //tell the template engine var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { // route for '/' var temp = 50; //here you assign temp variable with needed value var total = temp+10; res.render('index', { //render the index.ejs temp: temp, total:total }); }); var server = app.listen(3000, function() { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); }); 

HTML(重命名为index.ejs ):

 <html> <head> </head> <body> My temperature: <%= temp %> Temp + 10 : <%= total %> </body> </html>