how to direct a page synchronously at nodejs

Asked

Viewed 113 times

0

good afternoon I own a page called index.js in the route folder of the express nodejs.

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 handles the asynchronous code causing the variable not to 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();

  • mothod: 'GET', Is this a copy-to error or is that what you have in the options, really? try to exchange for method: 'GET'

  • adjusted but still does not work synchronously

2 answers

1


You can send the answer inside 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);
    });
  });
}

0

another way I found to do this was to run 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 making this JSON.parse(body) without this parse does not work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.