node.js 和电报机器人

node.js and telegram bot

我需要使用电报机器人来调用网站的路由。 在网站中,在 routes.js 中,我有:

app.get('/api/getalert', getAlert);

var getAlert = function(req, res) {
        var id = req.query.id;
        Alert.find({})
            .sort({
                "alertStatus.date": -1
            })
            .limit(1)
            .exec(
                function(err, alert) {
                    if (err) {
                        res.status(500).send(err)
                    };
                    console.log(JSON.stringify(alert, null, 4));
                    res.json(alert);
                });
    };

在我的电报机器人中:

bot.on("/alarm", msg => {
  let fromId = msg.from.id;

  var options = {
    host: "my.website",
    port: 3333,
    path: "/api/getalert"

  };

  var callback = function(res) {
    res.on("data", function(data) {
      console.log('data is '+data);
      console.log('name is: '+data.name);
    });
  }

  var req = http.get(options, callback)
    .on('error', function(e) {
      console.error(e);
    });
)};

bot.connect();

console.log(data)的结果类似这样:

data is 
[{
"_id":"585d08455733bb63a19b0b4d",
"name":"Alert",
"description":"Alert description",
"address":"an_address ",
"__v":0,
"alertStatus": 
    [{"_id":"585d08455733bb63a19b0b4c",
      "date":"2016-12-23T11:19:33.608Z",
      "status":1
    }],
"users":[42711895,85811757],
"range":1000,
"position":{"lat":11,"lng":12}
}]

但是。

使用 console.log(data[0]) 它只打印 91 .

使用 console.log(data.name) 它打印 undefined .

我做错了什么?

我想我找到了解决方案...我接收到数据块,然后合并单个块,然后在 'end' 上连接块并解析它们:

var callback = function(res) {
    var dataChunks = [];
    res.on('data', function(chunk) {
      dataChunks.push(chunk);
    })

    .on('end', function() {
      //obj will contain the objects received
      var obj = Buffer.concat(dataChunks);
      //all objects in JSON format
      var stringObj = JSON.parse(obj);
      //test to check if it works
      console.log(stringObj[0].users);
    })

  }