I’m working on a Telegram bot that should interact with a specific web API route. I’ve set up an endpoint in my application to retrieve alerts, but I’m having issues with accessing the data that gets returned.
On my server, I have defined this endpoint in the routes.js file:
app.get('/api/getalert', getAlert);
The corresponding function looks like this:
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);
});
};
In my Telegram bot, I’m attempting to call this endpoint:
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 received: ' + data);
console.log('alert name is: ' + data.name);
});
}
var req = http.get(options, callback)
.on('error', function(e) {
console.error(e);
});
});
bot.connect();
The API responds with JSON data looking like this:
[{"_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}}]
When I log the output, I see the data structure, but when I try console.log(data[0]), it returns just a number like 91. Also, console.log(data.name) results in undefined. What am I doing wrong in how I access this data?