koajs / koa-body

koa body parser middleware
MIT License
950 stars 130 forks source link

Request pending forever if content type is application/json #154

Open LeonAlvarez opened 5 years ago

LeonAlvarez commented 5 years ago

Problem/Feature Request Summary

Not able to parse request body when the header is application/json

Environment Information

Current Behavior

When request Content-Type header is application/json the request stay pending forever resolving. ,

Steps to Reproduce

const Router = require("koa-router"); const koaBody = require("koa-body")

Expected Behavior

application/json content parsed

Context (Environment)

For urlencoded or text request its working fine.

I tried to debug it and I can see the options passed to the co-body json https://github.com/dlau/koa-body/blob/ed81445ccd6d2e3b5e4605ce502b60c75386f8f5/index.js#L74 are:

{
   encoding: 'utf-8', 
   limit: '1mb',
   strict: true,
   returnRawBody: false
}
MarkHerhold commented 5 years ago

Can you confirm that the koa-router example works for you? We have the same basic setup.

https://github.com/dlau/koa-body/blob/master/examples/koa-router.js

LeonAlvarez commented 5 years ago

Yes, I'm using it in other routes with other content types and it works it also work on that one if I change the content type.

I just add the koa-router.js example to my project and it also works fine

MarkHerhold commented 5 years ago

I don't think we'll be able to troubleshoot this without an example repository.

ozziexsh commented 5 years ago

I can confirm we're experiencing this as well, but I should note that this only happens when we deploy to Google Cloud Functions, running locally works fine.

Reproducing this is pretty simple:

const koa = require("koa");
const koaBody = require("koa-body");
const KoaRouter = require("koa-router");

const app = new koa();

app.use(koaBody({ multipart: true }));

const router = new KoaRouter();

router.post("/", ctx => {
  ctx.body = ctx.request.body;
});

app.use(router.routes());

if (process.env.NODE_ENV !== "production") {
  app.listen(3222);
}

exports.callback = app.callback();

In postman if you enable the header Content-Type: application/json it hangs forever, but if you take it out then it responds immediately.

ozziexsh commented 5 years ago

Decided to spend some time and dig into this and was able to replicate it on the functions emulator.

Looks to be an issue with the ctx.req stream already being "read" and the raw-body dep doesn't handle that, see here:

https://github.com/stream-utils/raw-body/issues/57 https://github.com/stream-utils/raw-body/pull/58

Not sure what the solution is here though to actually get koa-body access to that data though...

Abourass commented 5 years ago

Same issue

damianobarbati commented 4 years ago

Same issue. It happens with HTTP2 connections?