How to pass data from node js to html.?
Solution 1
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
Solution 2
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}`);
Pradeep.T
Updated on June 29, 2022Comments
-
Pradeep.T almost 2 years
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