node.js и телеграмма бот

Мне нужно использовать бот-телеграмму для вызова маршрута веб-сайта. На сайте, в 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,

Что я делаю не так?

1 ответ

Решение

Я думаю, что у меня есть решение... Я получил данные кусками, затем объединил отдельные куски, затем на '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);
    })

  }
Другие вопросы по тегам