how to direct a page synchronously in nodeJS

0

Good afternoon I have a page called index.js in the route folder of nodejs express.

When the pendingAprovals page is called I would like the index to call a webservice to send a JSON to the pendingAprovals, but the node treats the asynchronous code causing the variable to not be populated.

below the code I have:

index.js

var options = {
    host: 'localHost',
    port: 7001,
    path: 'meuWebService/meuMetodo',
    mothod: 'GET',
    header: { 'Content-Type': 'application/json; charset=utf-8' }
};
var list =
    http.request(options, function(res) {
        var body = "";
        res.setEncoding('utf-8');
        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            list = JSON.parse(body);
            console.log(JSON.stringify(body));
        });
    });

list.end();
    
asked by anonymous 24.01.2017 / 14:59

2 answers

1

You can send the response within the request callback

function performRequest(callback){
  http.request(options, function(res) {
    var body = "";
    res.setEncoding('utf-8');
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      callback(body);
    });
  });
}
    
25.01.2017 / 09:11
0

Another way I found to do this was to execute the call as follows in the route file. (which in my case was index.js)

router.get('/solicitacoes', function(req, res, next) {
    if (!req.session.name) {
        return res.redirect('/');
    }
    var endereco = 'MeuWebService/MetodoGet'
    var name = req.session.name;
    request(endereco, (err, response, body) => {
        if (!err && response.statusCode == 200) {
            res.render('solicitacoes', {
                title: 'MeuTitulo',
                page: 'solicitacoes',
                list: JSON.parse(body),
                user: name,
                Config: config,
                modalData: ""
            });
        }
    });
});

An important part was to do this JSON.parse (body) without this parse does not work.

    
06.02.2017 / 14:28