1.前言
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
2.特点
避免安装依赖 直接进入代码 跳过setup 启动阶段 run fresh install script
3.对比fetch的优势
- Simpler API 简单的api
- Method shortcuts (
ky.post()
) 方法名称简写 - Treats non-2xx status codes as errors (after redirects) 将2.xx的状态码视为错误(在重定向之后)
- Retries failed requests 错误请求重试
- JSON option JSON的格式
- Timeout support 支持超时
- URL prefix option 请求地址支持前缀
- Instances with custom defaults 客服端默认实例配置
- Hooks 钩子函数
4.使用和安装
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';
5.API
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 theResponse
first. When called like that, an appropriateAccept
header will be set depending on the body method used. Unlike theBody
methods ofwindow.Fetch
;these will throw an
HTTPError
if 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 is204
instead 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?)
5.1详细介绍
5.1.1options
Type:object
5.1.2methods
Type:string
default:'get'
5.1.3json
Type:object or any other value accepted by Object.stringfiy
5.1.4searchParams
Type: string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams
Default: ''
5.1.5prefixUrl
Type: string | URL
A prefix to prepend to the
input
URL 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 wheninput
is a string. Theinput
argument 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解析规则,这会改变前导斜杠的含义。
5.1.6retry
Type: object | number
Default:
limit
:2
methods
:get
put
head
delete
options
trace
statusCodes
: 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();
5.1.7timeout
Type: number | false
Default: 10000
如果设置false,将不会使用timeout。timeout是毫秒级别的单位,设置为毫秒级。但是最大不能超过2147483647。
5.1.8hooks
Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}
在request整个生命周期里面,hooks允许任意的修改。hooks函数是连续的,异步的。
Type: Function[]
Default: []
- hooks.beforeRequest 接受request options?
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);
}
}
]
}
});
5.1.9 ky.extend(defaultOptions)
生成一个传入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
5.1.10ky.create(defaultOptions)
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'
5.1.11Cancellation 取消请求
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);
}
}
FAQ find answer and question
1.怎么在nodejs里面使用ky?
Check out ky-universal.
可以使用ky-universal,地址如下
ky-universalhttps://github.com/sindresorhus/ky-universal#faq2.怎么在没有打包工具的情况下使用ky,比如没有webpack?
Make sure your code is running as a JavaScript module (ESM), for example by using a
<script type="module">
tag in your HTML document. Then Ky can be imported directly by that module without a bundler or other tools.的代码需
首先你的代码需要运行在ESM下面,举个例子:使用
<script type="module">的标签
在你的html文档里面。然后这个ky可以在没有打包工具或者其他工具情况下直接导入。
3.ky与axios直接有什么区别?
6.完整的封装
6.1request.ts
import ky from 'ky';
import { requestCode } from './requestCode';
import message from '../components/message'
const api = ky.create({
prefixUrl: '/',
headers: {
'content-type': 'application/json',
},
hooks: {
beforeRequest: [
request => {
request.headers.set('X-Requested-With', 'ky');
}
],
afterResponse: [
(_request, _options, response) => {
if (response.status !== 200) {
console.log(response.status)
// TODO 提示错误信息
console.log(response, 'response');
console.log(requestCode, 'requestCode')
}
return response;
},
],
beforeError: [
(error: any) => {
const { response } = error;
console.log(response)
const { status } = response;
message.warning(requestCode[status])
if (response && response.body) {
// error.name = 'error';
// error.message = `${response.body.message} (${response.statusCode})`;
}
// TODO 提示错误信息
return error;
}
]
}
});
export default api;
requestCode.ts
export const requestCode = {
"400": "请用户刷新页面重试",
"401": "引导用户重新登陆",
"403": "引导用户联系管理员",
"404": "返回资源列表并更新列表",
"500": "提示用户服务系统错误,联系管理员,稍后再试",
"502": "提示用户服务系统错误,联系管理员,稍后再试",
"503": "提示用户服务系统错误,联系管理员,稍后再试",
}