elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
9.93k stars 211 forks source link

Error from body-parser when sent `Content-Type` header without body #771

Open assapir opened 1 month ago

assapir commented 1 month ago

What version of Elysia is running?

1.0.20

What platform is your computer?

Darwin 23.6.0 arm64 arm

What steps can reproduce the bug?

  1. Create a DELETE handler that does not expect a body, like:
    .delete('/:id', async ({ article }) => {
    await deleteArticle(article!.id);
    return {
    sessionId: article!.id,
    };
    });
  2. Send a request with a header of Content-Type: application/json

What is the expected behavior?

No failure, the handler will just be called

What do you see instead?

Failed to parse body as found: undefined is returned

Additional information

I think the fix should be - don't run the body parser if there is no content (the content-length header is absence or set to 0)

Have you try removing the node_modules and bun.lockb and try again yet?

yes, but when upgraded from 1.0.20 to 1.1.5 I always get Not Found on my routes, so I can't upgrade

kristjansuursoho commented 1 month ago

Quick fix

const elysia = new Elysia()
  .onParse(async ({ request, contentType }) => {
    try {
      if (contentType === 'application/json') {
        return await request.json()
      }
    } catch (error) {
      return request.text()
    }
  })
kravetsone commented 1 month ago

What version of Elysia is running?

1.0.20

What platform is your computer?

Darwin 23.6.0 arm64 arm

What steps can reproduce the bug?

  1. Create a DELETE handler that does not expect a body, like:
.delete('/:id', async ({ article }) => {
  await deleteArticle(article!.id);
  return {
    sessionId: article!.id,
  };
});
  1. Send a request with a header of Content-Type: application/json

What is the expected behavior?

No failure, the handler will just be called

What do you see instead?

Failed to parse body as found: undefined is returned

Additional information

I think the fix should be - don't run the body parser if there is no content (the content-length header is absence or set to 0)

Have you try removing the node_modules and bun.lockb and try again yet?

yes, but when upgraded from 1.0.20 to 1.1.5 I always get Not Found on my routes, so I can't upgrade

U shouldn't lie server about content-type)

kravetsone commented 1 month ago

But elysia can also check content-length

on1force commented 1 month ago

you can try to use the schema and just pass on t.Optional on the body, haven't tried this though.