I'm building an app using node.js + express + handlebars and was looking for a way i can pass handlebars data from the server to client-side javascript files. For example:
//server.js
var person = {
name: George,
age: 32,
}
res.render('../views/person', person)
I want to be able to use the person object on the client side such as:
//client.js
console.log(person.age);
console.log(person.name);
Can someone help?
Thanks!
try this
res.render('../views/person', {person: person})
If you're passing more than just a few objects, I would recommend building some sort of API around your client-server relationships using Express's routing ( http://expressjs.com/en/guide/routing.html )
// server
app.get('/person/a', function (req, res, next) {
console.log('the response will be sent by the next function ...');
next();
}, function (req, res) {
res.send({person: {age: 30, name: "Bob", greeting: "hello"}});
});
and your client would then call those routes with the http module ( https://nodejs.org/api/http.html ):
// client
http.get({
hostname: 'localhost',
port: 80,
path: 'person/a',
}, (res) => {
// Do stuff with response
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With