将handlebarsvariables传递给客户端js文件

我使用node.js + express + handlebars构build应用程序,并正在寻找一种方法,可以将句柄数据从服务器传递到客户端JavaScript文件。 例如:

//server.js

 var person = { name: George, age: 32, } res.render('../views/person', person) 

我希望能够在客户端使用person对象,例如:

//client.js

 console.log(person.age); console.log(person.name); 

有人可以帮忙吗?

谢谢!

尝试这个

  res.render('../views/person', {person: person}) 

如果你传递的不仅仅是几个对象,我会build议使用Express的路由( http://expressjs.com/en/guide/routing.html )在你的客户端 – 服务器关系周围build立一些API。

 // 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"}}); }); 

然后你的客户端会用http模块( https://nodejs.org/api/http.html )调用这些路由:

 // client http.get({ hostname: 'localhost', port: 80, path: 'person/a', }, (res) => { // Do stuff with response })