Variables between the HTML client and Node.js server

I just want to transfer the variables from the HTML page to node js and do some data calculations and return them to HTML using ejs After installing ejs:

npm install ejs

I am trying to pass this temp variable with a value of 50 "HTML page":

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

and my 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);

Any help would be appreciated Thanks in advance.

+4
source share
2 answers

In your server file, temp is undefined. So, total = undefined + 10 = undefined. Therefore, your variables are undefined in the server file. Try to do this (in the server file): var temp = 0 var total = 0

html My temperature: <%= temp = 50 %> Temp + 10 : <%= total = temp + 10 %> i.e 50 60. ,

+1

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>
0

Source: https://habr.com/ru/post/1622421/


All Articles