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

JSON body is not parsed when Content-Type contains a charset #341

Open
petercmuc opened this issue Jul 19, 2024 · 1 comment
Open

JSON body is not parsed when Content-Type contains a charset #341

petercmuc opened this issue Jul 19, 2024 · 1 comment

Comments

@petercmuc
Copy link

My back-end returns JSON data with a content-header that contains the suffix +json'and the charset=utf-8'
The content-type is not recognized as JSON and the body is returned as a plain string instead of JSON.

The problem is the way that the Content-Type header is parsed:
Content-Type: application/whatever+json;charset=utf-8

This is the method for parsing the header (and the body):

  protected parseBody(response: FetcherResponse): Promise<object | string> {
    const contentType = response.headers.get('Content-Type');
    const contentLength = response.headers.get('Content-Length');
    if (
      // As one might expect, a "204 No Content" is empty! This means there
      // isn't enough to `JSON.parse`, and trying will result in an error.
      response.status !== 204 &&
      contentLength !== '0' &&
      contentType &&
      (contentType.startsWith('application/json') ||
        contentType.endsWith('+json'))
    ) {
      return response.json();
    } else {
      return response.text();
    }
  }

The condition for checking on JSON fails, because:
contentType.endsWith('+json')
is false in the case that there is a charset defined at the end of the header

@slagiewka
Copy link

See #229.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants