sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
MIT License
11.83k stars 341 forks source link

How to handle HTTP Delete Method (204) with ky? #555

Closed zebra-f closed 6 months ago

zebra-f commented 6 months ago

This is my request:

async function requestDeleteAccount(id: string) {
  try {
    console.log("a");
    const response = await kyClient.backendApi.delete(`users/${id}/`, {
      retry: { limit: 0 },
    });
    console.log("b, response", response);
    const responseData = {};
    return { status: response.status, data: responseData };
  } catch (error: any) {
    try {
      console.log("c, error", error);
      const response = await error.response;
      console.log("d, response", response);
      const responseData = await response.json();
      console.log("e, responseData", responseData);
      console.log(responseData);
      return { status: 401, data: {} };
    } catch (_error: any) {
      console.log("f, error", _error);
      return { status: 500, data: {} };
    }
  }
}

Normally the 8th line would look like this:

const responseData = await response.json()

however looking through this issue I thought that only trying to access JSON response would throw an error that's why I changed the 8th line, yet this part:

const response = await kyClient.backendApi.delete(`users/${id}/`, {
      retry: { limit: 0 },
    });

already throws, here's what console.log() shows:

a
c, error SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data 
d, response undefined
f, error TypeError: response is undefined

I'm looking only to retrieve 204 status of the response, which my Backend returns (and Firefox shows correctly). What are my option (other than changing the response from my Backend)?

Edit: closed the issue, I just noticed that my afterResponse calls response.json()... sorry, you can delete it.