skip to Main Content

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


  1. You can merge responses together into one object and send it to jade:

    let output = {};
    for (let i = 0; i < results.length; i++) {
      output = { ...output, ...results[i] };
    }
    res.render('index', output);
    
    Login or Signup to reply.
  2. 👨‍🏫 You can make something like this code below 👇:

    var url = ApiConfiguration.getApiURL();
    var requests = [{
        url: url + '/api/team/members/',
        headers: {
            'headers': 'apitoken'
        }
    }, {
        url: url + '/api/service/',
        headers: {
            'headers': 'apitoken'
        }
    }];
    
    // I'm using Promise.map from 'bluebird'.
    // make sure it's same
    Promise.map(requests, function(obj) {
        return new Promise((resolve, reject) => {
            // I'm using request from: https://www.npmjs.com/package/request
            // make sure you too
            request(obj, function(err, res, body) {
                if (err) return reject(err);
                return resolve(JSON.parse(body));
            })
        })
    }).then(function(results) {
        const members = [];
        results.map(result => {
            if (result && result.team && result.team.length > 0) {
                result.team.forEach(team => {
                    members = [...members, ...team.members]
                })
            }
        });
    
        res.render('index', members);
    
    }).catch(ex => {
        console.log(ex.message);
        console.log(ex);
    })
    

    And now, in your .jade, you can make something like this code below 👇:

    doctype html
    html
        head
            title=title
        body
            h1 This page is produced by Jade engine
            p some paragraph here..
            if members
            each member in members
              .team-member
                  h4= member.name
    

    I hope it’s can help you 🙏.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search