koajs / bodyparser

Koa body parsing middleware
MIT License
1.31k stars 118 forks source link

Not working with Firebase Functions #127

Closed xxRockOnxx closed 1 year ago

xxRockOnxx commented 5 years ago

This is really puzzling because you can't really figure out why it's giving a Timeout.

No errors or warnings.

Fortunately, I stumbled upon this stackoverflow question: https://stackoverflow.com/questions/58237305/post-request-hangs-timeout-when-trying-to-parse-request-body-running-koa-on-f

And according to the solution written there:

Firebase already parses the body. https://firebase.google.com/docs/functions/http-events#read_values_from_the_request

It appears that the provided Koa body parsing middlewares don't know what to do with an "already parsed" body (ie an object vs an unparsed string), so the middleware ends up getting confused and does some sort of an infinite loop.

A solution is to use ctx.req.body because it's already parsed. :)

Shouldn't this package handle the said problem?

EDIT:

I mean at least a warning to prevent confusion if it can't do it. It doesn't make sense to use this package if the body is already parsed wouldn't it?

christophwitzko commented 4 years ago

I created a small middleware function to support already parsed bodies:

function hybridBodyParser (opts) {
  const bp = bodyParser(opts)
  return async (ctx, next) => {
    ctx.request.body = ctx.request.body || ctx.req.body
    return bp(ctx, next)
  }
}

Usage:

app.use(hybridBodyParser())
3imed-jaberi commented 4 years ago

I created a small middleware function to support already parsed bodies:

function hybridBodyParser (opts) {
  const bp = bodyParser(opts)
  return async (ctx, next) => {
    ctx.request.body = ctx.request.body || ctx.req.body
    return bp(ctx, next)
  }
}

Usage:

app.use(hybridBodyParser())

@dead-horse, @niftylettuce What do you think of adding this to the README.md file !!

niftylettuce commented 4 years ago

I am strongly against using anything like Firebase. It is up to @dead-horse on this.

xxRockOnxx commented 4 years ago

Using this on firebase does not make any sense since it'll not do anything. Firebase does it already. Although I know how to workaround this now, a warning on README would be appreciated by those who haven't come across this yet.

niftylettuce commented 4 years ago

Submit a PR for review

3imed-jaberi commented 1 year ago

I have already published a blog talking about this here and I will include this in my PR (#152) for the next release.

3imed-jaberi commented 1 year ago

I have added a new option enableRawChecking to support the already parsed body by checking the raw request ctx.req.body if it contains values (code).

3imed-jaberi commented 1 year ago

I would say, we published @koa/bodyparser v5 a few minutes ago. So you can now use the enableRawChecking option.