0

I would like to sent response from node server to client instead of greeting the return value of function Stats.calculate(), but I cannot figure out how to do it.

router.post('/calc', (req, res) => {      
    request.get('a secret url api', (err,res,bodyJson) => {
        if(err) console.log('error');
        if(res.statusCode !== 200 ) console.log('error');
        Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);
    });
    res.json({greeting: "ciao"});
});

Any suggestions?

xTomasM
  • 332
  • 2
  • 11

1 Answers1

2

You can just call res.json inside the callback:

router.post('/calc', (req, res) => {      
    request.get('a secret url api', (err, response, bodyJson) => {
        if(err) console.log('error');
        if(response.statusCode !== 200 ) console.log('error');
        var statsResult = Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);

        res.json({result: statsResult});
    });

});
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46