Skip to content
Myr

fix(request): keep the request media type when reusing a cached body (#5366)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(request): keep the request media type when reusing a cached body `HonoRequest` caches the parsed body so it can be read through more than one representation. The fallback that rebuilds a body from an already cached representation went through a bare `Response`: return new Response(body)[key]() A `Response` constructed that way has no `Content-Type`, so a representation that needs the media type could no longer be produced even though the bytes were still available: app.post('/', async (c) => { const raw = await c.req.text() // e.g. verify a signature first const form = await c.req.formData() // TypeError }) For an `application/x-www-form-urlencoded` or `multipart/form-data` request the second call threw `TypeError: Content-Type was not one of ...`. `c.req.blob()` was unaffected (a `Blob` carries its own type) and `c.req.parseBody()` was unaffected (it reads the media type from `req.raw.headers`), so the same app behaved differently depending on which accessor was used first. Carry the original `Content-Type` over when rebuilding the body. `FormData` is left alone, because `Response` has to generate a fresh multipart boundary for it. * refactor(request): check the cache key instead of instanceof FormData ---------

authored by Xia Chao · committed by GitHub · parent 9b4e9c2 · Browse files · 2 files+62 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Xia Chao <236466140+bun-unsafe@users.noreply.github.com>
  • Co-authored-by: Yusuke Wada <yusuke@kamawada.com>

Diff stats

2 files+62 added−1 removed

  • tests:+52 added−0 removed
  • other:+10 added−1 removed

2 files+62 added−1 removed

modified:src/request.test.ts+52 added
375 unmodified lines
376 expect(async () => await req.bytes()).not.toThrow()377 expect(async () => await req.blob()).not.toThrow()378 })379380 describe('formData() after another representation has been cached', () => {381 const urlencoded = 'application/x-www-form-urlencoded'382 const body = 'foo=bar&baz=qux'383384 for (const first of ['text', 'arrayBuffer', 'bytes', 'blob'] as const) {385 test(`req.formData() after req.${first}()`, async () => {386 const req = new HonoRequest(387 new Request('http://localhost', {388 method: 'POST',389 headers: { 'Content-Type': urlencoded },390 body,391 })392 )393 await req[first]()394 const formData = await req.formData()395 expect(formData.get('foo')).toBe('bar')396 expect(formData.get('baz')).toBe('qux')397 })398 }399400 test('req.formData() after req.text() for multipart/form-data', async () => {401 const boundary = '----hono-test-boundary'402 const multipart =403 `--${boundary}\r\n` +404 'Content-Disposition: form-data; name="foo"\r\n\r\n' +405 'bar\r\n' +406 `--${boundary}--\r\n`407 const req = new HonoRequest(408 new Request('http://localhost', {409 method: 'POST',410 headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },411 body: multipart,412 })413 )414 await req.text()415 expect((await req.formData()).get('foo')).toBe('bar')416 })417418 test('the cached representation is still returned unchanged', async () => {419 const req = new HonoRequest(420 new Request('http://localhost', {421 method: 'POST',422 headers: { 'Content-Type': urlencoded },423 body,424 })425 )426 expect(await req.text()).toBe(body)427 expect(await req.text()).toBe(body)428 expect(await req.arrayBuffer()).toEqual(new TextEncoder().encode(body).buffer)429 })430 })431432 describe('req.parseBody()', async () => {433 it('should parse form data', async () => {434 const data = new FormData()435 data.append('foo', 'bar')
316 unmodified lines
modified:src/request.ts+10 added-1 removed
225 unmodified lines
226 return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {227 if (anyCachedKey === 'json') {228 body = JSON.stringify(body)229 }230 // Rebuilding the body through a bare `Response` loses the request's media231 // type, so a representation that needs it (e.g. `formData()`) can no longer232 // be produced even though the bytes are still available. Carry the original233 // `Content-Type` over, except for `FormData`, where `Response` must generate234 // a fresh multipart boundary of its own.235 const contentType =236 anyCachedKey === 'formData' ? undefined : raw.headers.get('content-type')230 return new Response(body)[key]()237 return new Response(body, {238 headers: contentType ? { 'Content-Type': contentType } : undefined,239 })[key]()240 })241 }242243 return (bodyCache[key] = raw[key]())
277 unmodified lines