mswjs / http-middleware

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.

Home Page:https://npm.im/@mswjs/http-middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Incorrect content-length header with msw@^2.2.0 and unicode characters

aimee-gm opened this issue · comments

Background

Last week, msw@2.2.0 was released. As part of this, mswjs/msw#1996 (feat: automatically set "Content-Length" on text/json responses) was included.

This now adds a Content-Length header to all responses, calculated from body.length.toString()

The issue

On upgradeing to msw@2.2.1, I've been having an issue where the generated content-length is incorrect and my response has been truncated when using special characters.

I believe this affects all responses with unicode characters and breaks this package with the latest version of msw when suing unicode characters.

Reproduction

Use msw@^2.2.0

Modify the example to the following:

  http.post<LoginBody, LoginResponse>('/test', async ({ request }) => {
    const user = await request.json()
    const { username } = user

    return HttpResponse.json({
      username,
      firstName: 'John',
      company: 'CompanyName™',
    })
  }),

Output:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

The Content-Length was incorrectly calculated as 2 short.

Hi! Thanks for reporting this. This really belongs in the MSW repo.

Would the correct length of that unicode character be 3? Looks like we'd have to get the byte length instead of the string length in MSW as a bugfix. Waiting for you to confirm the expected length.