Hat hout
Hat hout

Reputation: 491

Variables between HTML Client and Node.js Server

I just wanna to pass variables from a HTML page to a node js and perform some calculations on the data and get it back to HTML using ejs After installing ejs :

npm install ejs

I'm trying to pass this variable temp with value 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.

Upvotes: 5

Views: 8310

Answers (2)

Alvaro Silvino
Alvaro Silvino

Reputation: 9743

You do not need this fs requirement.

All you need to do is :

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 (rename to index.ejs):

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

Upvotes: 0

Nischay Malhan
Nischay Malhan

Reputation: 111

In your server file, the value of temp is undefined. And so total = undefined + 10 = undefined. Hence both your variables are undefined in the server file. Try doing this (in the server file): var temp = 0 var total = 0

In the html file My temperature: <%= temp = 50 %> Temp + 10 : <%= total = temp + 10 %> Now it should display the correct value i.e 50 and 60. Hope this helps

Upvotes: 1

Related Questions