最全ky使用教程(基于fetch的小巧优雅js的http客服端)_ky axios,技术实现

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

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 the Response first.         When called like that, an appropriate Accept header will be set depending on the body method used. Unlike the Body methods of window.Fetch;

these will throw an HTTPError if the response status is not in the range of 200...299. Also, .json() will return an empty string if body is empty or the response status is 204 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 with input. Only takes effect when input is a string. The input 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:

  • limit2
  • methodsget put head delete options trace
  • statusCodes408 413 429 500 502 503 504
  • maxRetryAfterundefined

延迟重试的计算方法是使用: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: []

  1. 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);
//=> false

console.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 APIRead more.

for example:

img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化资料的朋友,可以戳这里获取

ion through the AbortController APIRead more.

for example:

[外链图片转存中…(img-SE3v31r2-1715091846414)]
[外链图片转存中…(img-CN98FPm1-1715091846415)]
[外链图片转存中…(img-Tzq2fQag-1715091846415)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化资料的朋友,可以戳这里获取

  • 18
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值