sindresorhus / ky
- пятница, 7 сентября 2018 г. в 00:15:59
JavaScript
Tiny and elegant HTTP client based on the browser Fetch API
Ky is a tiny and elegant HTTP client based on the browser Fetch API
Ky targets modern browsers. For older browsers, you will need to transpile and use a fetch
polyfill. For Node.js, check out Got.
1 KB (minified & gzipped), one file, and no dependencies.
fetch
ky.post()
)$ npm install ky
import ky from 'ky';
(async () => {
const json = await ky.post('https://some-api.com', {json: {foo: true}}).json();
console.log(json);
//=> `{data: '🦄'}`
})();
With plain fetch
, it would be:
(async () => {
class HTTPError extends Error {}
const response = await fetch('https://sindresorhus.com', {
method: 'POST',
body: JSON.stringify({foo: true}),
headers: {
'content-type': 'application/json'
}
});
if (!response.ok) {
throw new HTTPError(`Fetch error:`, response.statusText);
}
const json = await response.json();
console.log(json);
//=> `{data: '🦄'}`
})();
The input
and options
are the same as fetch
, with some exceptions:
credentials
option is same-origin
by default, which is the default in the spec too, but not all browsers have caught up yet.Returns a Response
object with Body
methods added for convenience. So you can, for example, call ky.json()
directly on the Response
without having to await it first. Unlike the Body
methods of window.Fetch
; these will throw an HTTPError
if the response status is not in the range 200...299
.
Type: Object
Type: Object
Shortcut for sending JSON. Use this instead of the body
option. Accepts a plain object which will be JSON.stringify()
'd and the correct header will be set for you.
Sets options.method
to the method name and makes a request.
Type: number
Default: 2
Retry failed requests made with one of the below methods that result in a network error or one of the below status codes.
Methods: GET
PUT
HEAD
DELETE
OPTIONS
TRACE
Status codes: 408
413
429
500
502
503
504
Type: number
Default: 10000
Timeout in milliseconds for getting a response.
Create a new ky
instance with some defaults overridden with your own.
Type: Object
Exposed for instanceof
checks. The error has a response
property with the Response
object.
The error thrown when the request times out.
Fetch (and hence Ky) has built-in support for request cancelation through the AbortController
API. Read more.
Example:
import ky from 'ky';
const controller = new AbortController();
const {signal} = controller;
setTimeout(() => controller.abort(), 5000);
(async () => {
try {
console.log(await ky(url, {signal}).text());
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
}
})();
r2
?See my answer in #10.
The latest version of Chrome, Firefox, and Safari.
MIT © Sindre Sorhus