sstur / nbit

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers
65 stars 4 forks source link

`Unexpected end of JSON input` when using `request.json()` with empty body #5

Closed ImLunaHey closed 1 year ago

ImLunaHey commented 1 year ago

It would be nice if we didn't need a try/catch around this for an empty body and instead an empty body would produce a null/undefined.

const body = await request.json();
sstur commented 1 year ago

The reason for the current behavior is that I tried to adhere as closely as possible to the standard Request class that's in modern JS engines including the browser.

For example, if you open your dev console in your browser and do the following:

const request = new Request('http://127.0.0.1/', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '' })
const data = request.json()

You'll notice it throws an error because the empty string can't be parsed as JSON.

I'd be open to special-case the empty string if other frameworks (e.g. Cloudflare workers or Bun) are doing this, or if there's an otherwise really strong case for it, but for now I'll close this as standards-compliant.

Screenshot 2023-08-02 at 08 51 36