MadPhysicist MadPhysicist - 1 month ago 6
Javascript Question

Extracting Information Sent Using res.json From a Node + Express API

I am building a relatively simple end-point that should return a number after doing a brief database query and a calculation. The problem is that I am uncertain on how I should send it to the front-end, so it is easily accessible there. In particular, I have been using the

res.json()
method, but when
console.log
'ed, it returns a huge object with the data in question nowhere to be found.

How can I go about sending data from API and accepting it on the front end? That is, I assume it will come as JSON, but I am wondering about unpacking it.

Here is the code:

router.get('/current/:id', function(req, res){
var collection = db.get('Activity');

var started = false;
var seconds;

//Important to use findOne here to get an object back instead of an array
collection.findOne({_id : req.params.id }, function(err, activity){
if (err) throw err;
var dateNow = (new Date()).getTime();
console.log("activity in /current/:id is: " + activity);
if (activity.runtime) {
var dateStart = (Date.parse(activity.runtime.startDate));
seconds = Math.round((dateNow - dateStart) / 1000);
started = activity.runtime.started;
console.log("dateNow: " + dateNow);
console.log("dateStart " + dateStart);
console.log("seconds " + seconds);
console.log(activity.runtime.started);
} else {
started = false;
seconds = 0;
}

if (started && (seconds > 0)) {
//res.json(seconds);
console.log(res.json(seconds));
}
else {
//res.json(0);
console.log(res.json(seconds));
}
});
});

Answer

You only need to be care of response content, you can send the response in this way :

 if (started && (seconds > 0)) {
     console.log(seconds);
     res.send({data : seconds});
 }else {
     res.send({data : 0});
  }

and the client will receive the data as:

{data : 0}
Comments