I am facing a issue at getting results from a REST api requests that return JSON objects.
How am I getting the results in jade template?
if team
each member in team[0].members
.team-member
h4= member.name
How is the data format for this object?
{
"team": [
{
"_id": "5e22f66a77011b3350a3285f",
"members": [
{
"_id": "5e264e4897534916ad8594a1",
"email": "[email protected]",
"name": "name",
"role": "Project Manager",
"twitter": "https://twitter.com/",
"facebook": "https://www.facebook.com/",
"linkedin": "https://www.linkedin.com/in//"
}
]
}
]
}
This is working fine, but I need more than one request. That is, there is more than one JSONs objects.
So, I have two requests to call in a same controller where each one returns a JSON object. I have implemented an approach that uses promises so that I can wait the requests to finish and after that I can store the output of each request in an array so that I can render only once.
How do I render the data?
for (var i = 0; i < results.length; i++) {
res.render('index', results[i]); // I cannot do it!
}
I can’t do it because I get some error regarding headers sent more than once: it returns a error of the kind => ERR_HTTP_HEADERS_SENT
How can I render without any error about headers?
var output = [];
for (var i = 0; i < results.length; i++) {
output.push(results[i]);
//res.render('index', results[i]);
}
res.render('index', output);
But now I can’t acess “team” neither “member” structure in JSON object.
How would I iterate over it?
== EDIT ==
After getting some answers, I think I have to share more details about the code. It is as follows:
var url = ApiConfiguration.getApiURL();
var requests = [{
url: url + '/api/team/members/',
headers: {'headers': 'apitoken'}},
{
url: url + '/api/service/',
headers: {'headers': 'apitoken'}}
];
Promise.map(requests, function (obj) {
return request(obj).then(function (body) {
return JSON.parse(body);
});
}).then(function (results) {
var output = [];
for (var i = 0; i < results.length; i++) {
output.push(results[i]);
//res.render('index', results[i]);
}
res.render('index', output);
}, function (err) {
if (err)
console.log(err);
});
2
Answers
You can merge responses together into one object and send it to jade:
👨🏫 You can make something like this code below 👇:
And now, in your
.jade
, you can make something like this code below 👇:I hope it’s can help you 🙏.