Telegraf: Note that BodyParsers will break Express WebhookCallback Function in Docs

Created on 30 Jun 2018  路  3Comments  路  Source: telegraf/telegraf

I was trying to integrate Telegraf into an ExpressJS server and having a terrible time because it seemed like the route was swallowing the request. After digging around in the webhook.js function I discovered that it was my BodyParser.json() that was messing up the request.

Would be very helpful to have this warning in the documentation with a solution. I fixed it by editing the webhook.js function to just use the req.body instead of parsing down the raw body. Could maybe even have a bodyParser = true flag in an option object fed to that function that tells the function to just use req.body.

My modification:

module.exports = function (hookPath, updateHandler, errorHandler) {
  return (req, res, next) => {
    debug('Incoming request', req.method, req.url)
    if (req.method !== 'POST' || req.url !== hookPath) {
      if (typeof next === 'function') {
        return next()
      }
      res.statusCode = 403
      return res.end()
    }
    const update = req.body
    updateHandler(update, res)
      .then(() => {
        if(!res.finished) {
          res.end()
        }
      })
      .catch(err => {
        debug('Webhook error', err)
        res.writeHead(500)
        res.end()
      })
  }
}
bug discussion enhancement

Most helpful comment

I spent so many hours trying to figure out why the hell nothing happens even though the requests arrive. Thank you @agstover

if you're using bodyparser then this is enough:

    app.post(`/secret-path`, (req, res) => {
        return bot.handleUpdate(req.body, res)
    })

All 3 comments

You really saved me a lot of stress

I spent so many hours trying to figure out why the hell nothing happens even though the requests arrive. Thank you @agstover

if you're using bodyparser then this is enough:

    app.post(`/secret-path`, (req, res) => {
        return bot.handleUpdate(req.body, res)
    })

I spent so many hours trying to figure out why the hell nothing happens even though the requests arrive. Thank you @agstover

if you're using bodyparser then this is enough:

    app.post(`/secret-path`, (req, res) => {
        return bot.handleUpdate(req.body, res)
    })

We need that small piece of documentation. A big warning not to use body-parser or express.json(). Thanks for your solution @MrToph it worked really well for me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sijie123 picture sijie123  路  3Comments

bostrot picture bostrot  路  3Comments

MohGanji picture MohGanji  路  3Comments

alkhimey picture alkhimey  路  3Comments

kuhel picture kuhel  路  3Comments