elysiajs / elysia

Ergonomic Framework for Humans

Home Page:https://elysiajs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

assapir opened this issue · comments

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

Quick fix

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

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)

But elysia can also check content-length

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