Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: set correct "Content-Length" response header for special characters (#2045) #2046

Merged
merged 3 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/core/HttpResponse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ describe('HttpResponse.text()', () => {
})
})

it('creates a text response with special characters', async () => {
const response = HttpResponse.text('안녕 세상', { status: 201 })

expect(response.status).toBe(201)
expect(response.statusText).toBe('Created')
expect(response.body).toBeInstanceOf(ReadableStream)
expect(await response.text()).toBe('안녕 세상')
expect(Object.fromEntries(response.headers.entries())).toEqual({
'content-length': '13',
'content-type': 'text/plain',
})
})

it('allows overriding the "Content-Type" response header', async () => {
const response = HttpResponse.text('hello world', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
Expand Down Expand Up @@ -68,6 +81,19 @@ describe('HttpResponse.json()', () => {
})
})

it('creates a json response given an object with special characters', async () => {
const response = HttpResponse.json({ firstName: '제로' })

expect(response.status).toBe(200)
expect(response.statusText).toBe('OK')
expect(response.body).toBeInstanceOf(ReadableStream)
expect(await response.json()).toEqual({ firstName: '제로' })
expect(Object.fromEntries(response.headers.entries())).toEqual({
'content-length': '22',
'content-type': 'application/json',
})
})

it('creates a json response given an array', async () => {
const response = HttpResponse.json([1, 2, 3])

Expand Down
4 changes: 2 additions & 2 deletions src/core/HttpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class HttpResponse extends Response {
if (!responseInit.headers.has('Content-Length')) {
responseInit.headers.set(
'Content-Length',
body ? body.length.toString() : '0',
body ? new Blob([body]).size.toString() : '0',
)
}

Expand Down Expand Up @@ -95,7 +95,7 @@ export class HttpResponse extends Response {
if (!responseInit.headers.has('Content-Length')) {
responseInit.headers.set(
'Content-Length',
responseText ? responseText.length.toString() : '0',
responseText ? new Blob([responseText]).size.toString() : '0',
)
}

Expand Down
Loading