将JSON数据发布到呈现页面

时间:2013-10-16 19:06:35

标签: javascript node.js post express get

我从URL获取我的搜索结果为JSON格式:“/ accounts /:id / users”我需要检索该JSON数据以呈现“/ contacts / find”。 (后一页显示搜索结果。)

这是我的应用路由器。有了这个,我可以在JSON格式的/ contacts / find中看到搜索结果:

app.post('/contacts/find', function(req, res) {
  var searchStr = req.param('searchStr', null);
  if ( null == searchStr ) {
    res.send(400);
    return;
  }

  models.Account.findByString(searchStr, function onSearchDone(err,accounts) {
    if (err || accounts.length == 0) {
      res.send(404);
    } else {
      res.send(accounts);
    }
  });
});

如何使用“帐户”(采用JSON格式)并使用帐户信息重新呈现页面?我正在尝试使用下面的代码段,但它不起作用。

app.get('/contacts/find', function(req, res) {
 res.render('searchResult.ejs', {
  accounts: req.accounts,
  email: req.accounts.email
 })
}

app.get方法无效。该URL只显示JSON数据。

1 个答案:

答案 0 :(得分:1)

所以accounts是一个JSON字符串?在这种情况下,您可以解析它(将其转换回对象)并将结果传递给您的模板:

var accounts = JSON.parse(req.accounts);
res.render('searchResult.ejs', {
  accounts : accounts,
  email    : accounts.email
 })