从Node + Express API提取使用res.json发送的信息

时间:2016-10-07 18:19:17

标签: javascript json node.js express

我正在构建一个相对简单的端点,它应该在执行简短的数据库查询和计算后返回一个数字。问题是我不确定如何将它发送到前端,所以它很容易在那里访问。特别是,我一直在使用res.json()方法,但是当console.log编辑时,它会返回一个巨大的对象,无法找到有问题的数据。

如何从API发送数据并在前端接受它?也就是说,我认为它将以JSON的形式出现,但我想知道解压缩它。

以下是代码:

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));
        }
    });
});

1 个答案:

答案 0 :(得分:1)

您只需关注响应内容,就可以通过以下方式发送响应:

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

,客户端将收到以下数据:

{data : 0}