react项目更加倾向于使用原生的fetch请求方式,而ky正是底层使用fetch的api做请求。github星数是8.2K,源码地址是:GitHub - sindresorhus/ky: 🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
特点是delightful 使用者快乐愉快,delightful http requests;
ky is a tiny and elegant HTTP client based on the browser Fetch API
ky是一个小巧而优雅基于浏览器的fetch api的http客服端。
大小只有3.1kb,ky的目标是现代浏览器和deno,deno是ts和js的一个现代运行时,更加简单和快捷,官网地址:Deno — A modern runtime for JavaScript and TypeScript
ky在日语里面是没眼力劲,认识不清当前局势的意思,安培晋三真的是ky
避免安装依赖 直接进入代码 跳过setup 启动阶段 run fresh install script
ky.post()) 方法名称简写installation
pnpm install ky or npm install ky or yarn add ky
usage
import ky from 'ky'
// examples
const json = ky.get('https://example.com',params).json();
params 是一个对象
如果是使用原生的fetch,将会是如下代码:
class HTTPError extends Error{}
const response = await fetch("https://example.com",{
method:'post',
body:JSON.stringfiy({foo:true}),
headers:{
'content-type':'application/json'
}
});
if(!response.ok) {
throw new HTTPErrror(`Fetch error: ${response.statusText}`)
}
const json = await response.json()
使用CDN:
import ky from 'https://esm.sh/ky';
1.ky(input,options?)
more options,see it below
Returns a Response object with Body methods added for convenience. So you can, for example, call
ky.get(input).json()directly without having to await theResponsefirst. When called like that, an appropriateAcceptheader will be set depending on the body method used. Unlike theBodymethods ofwindow.Fetch;these will throw an
HTTPErrorif the response status is not in the range of200...299. Also,.json()will return an empty string if body is empty or the response status is204instead of throwing a parse error due to an empty body.为了方便 使用body方法返回一个响应对象,你也可以,举个列子,直接使用key.get(input).json不需要事先等待返回结果。
当我们这样做的时候,将会适当的使用主体的方法来设置请求头部,不像window.fetch的主体方法。
如果http的状态码的范围在200到299之间将会抛出一个请求错误码,当然,.json()的方法也会返回一个空的字符串如果body是空的或者这个响应状态是204替代抛出一个解析的错误码由于是一个空的主体。
2.ky.get(input,options?)
3.ky.post(input,options?)
4.ky.put(input,options?)
5.ky.patch(input,options?)
6.ky.head(input,options?)
7.ky.delete(input,options?)
Type:object
Type:string
default:'get'
Type:object or any other value accepted by Object.stringfiy
Type: string | object
Default: ''
Type: string | URL
A prefix to prepend to the
inputURL when making the request. It can be any valid URL, either relative or absolute. A trailing slash/is optional and will be added automatically, if needed, when it is joined withinput. Only takes effect wheninputis a string. Theinputargument cannot start with a slash/when using this option.这是当你发生请求时候,一个拼接到URL前面的前缀。它可以是任何的URL,无论是绝对的还是相对的,一个尾部斜线是个选项,可以被自动添加。如果是需要的,当它被添加到input里面,仅仅是input是字符串的时候才会产生影响,当使用该选项的时候这个input属性不能以斜线开头。
for example: 举例:
import ky from 'ky';
// On https://example.com
const response = await ky('unicorn', {prefixUrl: '/api'});
//=> 'https://example.com/api/unicorn'const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
在前缀URL和输入连接后,将根据页面的URL(如果有)解析结果。
当使用此选项来加强一致性并避免混淆如何处理输入URL时,不允许使用输入中的前导斜杠,因为在使用前缀URL时,输入不会遵循正常的URL解析规则,这会改变前导斜杠的含义。
Type: object | number
Default:
limit: 2methods: get put head delete options tracestatusCodes: 408 413 429 500 502 503 504maxRetryAfter: undefined延迟重试的计算方法是使用:retry的次数是从1开始计算,层次从1开始计算
0.3 * (2 ** (retry - 1)) * 1000
重试不会触发使用一个timeout
import ky from 'ky';
const json = await ky('https://example.com', {
retry: {
limit: 10,
methods: ['get'],
statusCodes: [413]
}
}).json();
Type: number | false
Default: 10000
如果设置false,将不会使用timeout。timeout是毫秒级别的单位,设置为毫秒级。但是最大不能超过2147483647。
Type: object
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}
在request整个生命周期里面,hooks允许任意的修改。hooks函数是连续的,异步的。
Type: Function[]
Default: []
import ky from 'ky';
const api = ky.extend({
hooks: {
beforeRequest: [
request => {
request.headers.set('X-Requested-With', 'ky');
}
]
}
});
const response = await api.get('https://example.com/api/users');
1.hooks.beforeRetry
import ky from 'ky';
const response = await ky('https://example.com', {
hooks: {
beforeRetry: [
async ({request, options, error, retryCount}) => {
const token = await ky('https://example.com/refresh-token');
request.headers.set('Authorization', `token ${token}`);
}
]
}
});
2.hooks.beforeError
import ky from 'ky';
await ky('https://example.com', {
hooks: {
beforeError: [
error => {
const {response} = error;
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.status})`;
}return error;
}
]
}
});
3. hooks.afterResponse
import ky from 'ky';
const response = await ky('https://example.com', {
hooks: {
afterResponse: [
(_request, _options, response) => {
// You could do something with the response, for example, logging.
log(response);// Or return a `Response` instance to overwrite the response.
return new Response('A different response', {status: 200});
},// Or retry with a fresh token on a 403 error
async (request, options, response) => {
if (response.status === 403) {
// Get a fresh token
const token = await ky('https://example.com/token').text();// Retry with the token
request.headers.set('Authorization', `token ${token}`);return ky(request);
}
}
]
}
});
生成一个传入option对象的重写默认值新的ky实例,相比之下 in contrast,
import ky from 'ky';
const url = 'https://sindresorhus.com';
const original = ky.create({
headers: {
rainbow: 'rainbow',
unicorn: 'unicorn'
}
});const extended = original.extend({
headers: {
rainbow: undefined
}
});const response = await extended(url).json();
console.log('rainbow' in response);
//=> falseconsole.log('unicorn' in response);
//=> true
Create a new Ky instance with complete new defaults.
生成一个带有全部默认配置的新的ky实例。
import ky from 'ky';
// On https://my-site.com
const api = ky.create({prefixUrl: 'https://example.com/api'});
const response = await api.get('users/123');
//=> 'https://example.com/api/users/123'const response = await api.get('/status', {prefixUrl: ''});
//=> 'https://my-site.com/status'
Fetch (and hence Ky) has built-in support for request cancellation through the AbortController API. Read more.
for example:
import ky from 'ky';
const controller = new AbortController();
const {signal} = controller;setTimeout(() => {
controller.abort();
}, 5000);try {
console.log(await ky(url, {signal}).text());
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
}
1.怎么在nodejs里面使用ky?
Check out ky-universal.
可以使用ky-universal,地址如下
ky-universal
https://github.com/sindresorhus/ky-universal#faq2.怎么在没有打包工具的情况下使用ky,比如没有webpack?
Make sure your code is running as a JavaScript module (ESM), for example by using a
tag in your HTML document. Then Ky can be imported directly by that module without a bundler or other tools.的代码需
首先你的代码需要运行在ESM下面,举个例子:使用