简体   繁体   中英

Post JSON data to render page

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM