Skip to content

JSON Serialization error on 204 application/json with empty body #876

Description

@superr-fluous

Version: 2.0.2
Browser: Chrome (Brave)

Hi! I am currently facing an issue when my server responds with a 204 No Content while simultaneously sending content-type: application/json, which results in "Unexpected end of JSON input" error.

From #732 my understanding is that Ky is supposed to shortcut on 204 and empty responses to avoid calling unnecessary json decoding. However, since that issue and subsequent PR, some changes were introduced and now empty JSON responses are handled with JSON.parse (if no schema is passed):

const response = await result;

if (type !== 'json') {
  return ky.#raceBodyRead(async () => response[type](), response);
}

const text = await ky.#raceBodyRead(async () => response.text(), response) as string;
const request = ky.#getResponseRequest(response);
return ky.#raceWithTotalTimeout(async () => {
  if (text === '') {
    if (schema !== undefined) {
      return validateJsonWithSchema(undefined, schema);
    }
    // if type === 'json` and text === '', which is always going to throw an Error
    return JSON.parse(text);
  }

I believe that at the end there should be return undefined (null, "" or whatever).
OR
a check for custom parseJson which would handle the case.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions