sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[BUG] When Response is a string(not valid JSON), `json` method occurs error

alstn2468 opened this issue · comments

  • Example
const instance = ky.create({});

// URL returns string 'OK'
instance.get(URL).text();
  • Error Message
VM21639:1 Uncaught (in promise) SyntaxError: Unexpected token 'O', "OK" is not valid JSON

Same as when useJSON.parse('OK')

  • How to solve

https://github.com/sindresorhus/ky/blob/main/source/core/Ky.ts#L81

A try-catch block may be needed when the type is json.
Now, it seems that the code has been written to ensure that the API response value is JSON.
If an error occurs while call json method, it would be good to return empty object.

  • Temporary solution
instance.get(URL, { parseJson: (text) => text }).text();