Skip to content

Commit eb3e284

Browse files
authoredFeb 27, 2024··
fix: set correct "Content-Length" response header for special characters (#2045) (#2046)
1 parent 23fc364 commit eb3e284

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed
 

‎src/core/HttpResponse.test.ts

+26
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@ describe('HttpResponse.text()', () => {
2727
})
2828
})
2929

30+
it('creates a text response with special characters', async () => {
31+
const response = HttpResponse.text('안녕 세상', { status: 201 })
32+
33+
expect(response.status).toBe(201)
34+
expect(response.statusText).toBe('Created')
35+
expect(response.body).toBeInstanceOf(ReadableStream)
36+
expect(await response.text()).toBe('안녕 세상')
37+
expect(Object.fromEntries(response.headers.entries())).toEqual({
38+
'content-length': '13',
39+
'content-type': 'text/plain',
40+
})
41+
})
42+
3043
it('allows overriding the "Content-Type" response header', async () => {
3144
const response = HttpResponse.text('hello world', {
3245
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
@@ -68,6 +81,19 @@ describe('HttpResponse.json()', () => {
6881
})
6982
})
7083

84+
it('creates a json response given an object with special characters', async () => {
85+
const response = HttpResponse.json({ firstName: '제로' })
86+
87+
expect(response.status).toBe(200)
88+
expect(response.statusText).toBe('OK')
89+
expect(response.body).toBeInstanceOf(ReadableStream)
90+
expect(await response.json()).toEqual({ firstName: '제로' })
91+
expect(Object.fromEntries(response.headers.entries())).toEqual({
92+
'content-length': '22',
93+
'content-type': 'application/json',
94+
})
95+
})
96+
7197
it('creates a json response given an array', async () => {
7298
const response = HttpResponse.json([1, 2, 3])
7399

‎src/core/HttpResponse.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export class HttpResponse extends Response {
6363
if (!responseInit.headers.has('Content-Length')) {
6464
responseInit.headers.set(
6565
'Content-Length',
66-
body ? body.length.toString() : '0',
66+
body ? new Blob([body]).size.toString() : '0',
6767
)
6868
}
6969

@@ -95,7 +95,7 @@ export class HttpResponse extends Response {
9595
if (!responseInit.headers.has('Content-Length')) {
9696
responseInit.headers.set(
9797
'Content-Length',
98-
responseText ? responseText.length.toString() : '0',
98+
responseText ? new Blob([responseText]).size.toString() : '0',
9999
)
100100
}
101101

0 commit comments

Comments
 (0)
Please sign in to comment.