Reputation: 321
How can I simply pass a variable from node js to html and display it in the page? What is the simple mechanism. I am trying to develop a simple to-do list using node js
Upvotes: 2
Views: 15116
Reputation: 788
Try this, it may help you.
The Following function will bind your dynamic data to html
function doDataBinding(data, databindings){
for(var prop in databindings)
if( databindings.hasOwnProperty(prop) )
data = data.split('${'+prop+'}').join(databindings[prop]);
return data;
}
Sample request to verify dynamic data binding is as follows
app.use('/*', function(req, res){
//sample binding data
var dataToBind = { 'msg' : 'You\'ve been logged out successfully.' , 'error' : 'The username and password that you entered don\'t match.' };
res.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile( __dirname + '/login.html', 'utf8' ,function(err, data) {
if (err) throw err;
data = doDataBinding(data,dataToBind);
res.write(data);
res.end();
});
});
Try with login.html which is having ${msg} and ${error} data bindings.
Upvotes: 0
Reputation: 267
There are two approaches here you can use to view data from node( server side ) to html:
1- You could create a file in node which return data in json, then from JQuery you could do an ajax call this page and replace parts of the HTML with it. Sample code in node js:
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});
Ajax call:
$.get( "/users", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
2- You could use express with Jade ( I recommend http://expressjs.com/ )
Here is my blog on how to get started with node.js Click Here I created a starter kit for nodejs If you are interested Click Here
Upvotes: 2
Reputation: 1567
Establish a route and use res.send
method to respond with html content. The html content can use es2015 templates to include a variable in response. So it would look like:
const name = 'pradeep';
res.send(`hello ${name}`);
Upvotes: 1