Using a Telegram bot to access a web API route in Node.js

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?

yeah, sounds like you’re working with buffer stuff. try using axios or fetch over http.get for ease. also, check your endpoint in a browser to confirm it’s returning what you expect!

The problem is HTTP response data comes in as Buffer chunks, not parsed JSON. When you hit data[0], you’re just getting the ASCII value of the first character in that buffer. I’ve been there - ran into this exact thing building my first bot integration.

You need to collect all the chunks before parsing. Here’s a cleaner way that sets the encoding upfront:

var callback = function(res) {
  res.setEncoding('utf8');
  let rawData = '';
  
  res.on('data', (chunk) => {
    rawData += chunk;
  });
  
  res.on('end', () => {
    const alertData = JSON.parse(rawData);
    console.log('alert name is: ' + alertData[0].name);
  });
}

This way you skip the buffer-to-string headaches that can mess up parsing when there’s special characters.

Your problem is how Node.js handles HTTP responses. That data parameter in your callback is a Buffer with raw bytes, not parsed JSON. When you hit data[0], you’re grabbing the first byte value (91 = the ‘[’ character).

You need to collect all data chunks first, then parse the complete JSON string:

var callback = function(res) {
  let body = '';
  res.on('data', function(chunk) {
    body += chunk;
  });
  
  res.on('end', function() {
    try {
      const jsonData = JSON.parse(body);
      console.log('alert name is: ' + jsonData[0].name);
    } catch (error) {
      console.error('JSON parse error:', error);
    }
  });
}

Or just use axios - it handles JSON parsing automatically and makes HTTP requests way simpler.