Post JSON data to render page

不羁岁月 提交于 2019-12-12 03:06:21

问题


I am getting my search result as JSON format from the URL: "/accounts/:id/users" and I need to retrieve that JSON data to render "/contacts/find". (The latter page shows search results.)

Here is my app router. With this I could see the result of the search in /contacts/find in JSON format:

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

How can I use "accounts" (in JSON format) and re-render the page with the account info? I am trying with the below code snippet, but it does not work.

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

The app.get method is not working. The URL just shows JSON data.


回答1:


So accounts is a JSON string? In that case, you can parse it (to convert it back to an object) and pass the result to your template:

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


来源:https://stackoverflow.com/questions/19411697/post-json-data-to-render-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!