sindresorhus / ky

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

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

Closed alstn2468 closed 5 months ago

alstn2468 commented 5 months ago
const instance = ky.create({});

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

Same as when useJSON.parse('OK')

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.

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