ky使用教程(基于fetch的小巧优雅js的http客服端)

news2024/9/25 7:19:51

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 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
  • statusCodes: 408 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 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-universalicon-default.png?t=M85Bhttps://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": "提示用户服务系统错误,联系管理员,稍后再试",

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/31981.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

树上背包dp

“我们终其一生不过是为了一个AC罢了” 软件安装 嗯…这个题又调了一个下午&#xff0c;不过俺的确对dp方程有了一些理解 这个题没啥难的&#xff0c;不过是这个转移方程不太好想&#xff0c;过于抽象了&#xff0c;之前一直不理解树上背包是啥&#xff0c;现在理解了&#xff…

Xftp 无法连接 Debian

Xftp 无法连接 Debian检查网络是否配置有问题检查是不是防火墙没有关闭首先检查主机防火墙检查Debian防火墙启动SSH服务检查网络是否配置有问题 发现主机和Debian在一个网段。说明配置没有问题。 检查是不是防火墙没有关闭 首先检查主机防火墙 检查Debian防火墙 显然都没有开…

并行多核体系结构基础知识

目录分类MIMD计算机分类并行编程并行编程模型共享存储并行模型针对LDS的并行编程存储层次结构缓存一致性和同步原语缓存一致性基础对同步的硬件支持存储一致性模型和缓存一致性解决方案存储一致性模型高级缓存一致性设计互连网络体系结构分布式操作系统SIMT体系结构分类 根据Fl…

MCE | 磁珠 VS 琼脂糖珠

琼脂糖珠 长久以来&#xff0c;多孔的琼脂糖珠 (也称琼脂糖树脂) 作为免疫沉淀实验中的固相支持物常用的材料。琼脂糖珠海绵状的结构 (直径 50-150 μm) 可以结合抗体 (继而结合靶蛋白)&#xff0c;它能够直接高效、快速结合抗体&#xff0c;而不需借助特殊的专业设备。 图 1.…

【.Net Core】上传文件-IFormFile

文章目录安全注意事项存储方案文件上传方案.NET Core Web APi FormData多文件上传&#xff0c;IFormFile强类型文件灵活绑定验证内容验证文件扩展名验证文件签名验证文件名安全大小验证使名称属性值与 POST 方法的参数名称匹配来源安全注意事项 向用户提供向服务器上传文件的功…

openfeign调用文件服务的文件上传接口报错:Current request is not a multipart request

今天在用Swagger测试项目中文件服务的文件上传接口时发现接口调用异常。 异常展示 笔者这里罗列下Swagger上的错误显示、文件服务的异常以及服务调用方的异常。 【Swagger的异常】 【服务调用方的控制台异常】 【文件服务的控制台异常】 代码展示 【服务调用方的Controller…

KMP算法(求解字符串匹配)

提示&#xff1a;可搭配B站比特大博哥视频学习&#xff1a;传送门 &#xff08;点击&#xff09; 目录 前言 图解 代码 前言 KMP算法是一种改进的字符串匹配算法&#xff0c;由D.E.Knuth&#xff0c;J.H.Morris和V.R.Pratt提出的&#xff0c;因此人们称它为克努特一莫里斯―…

如何实现办公自动化?

办公自动化&#xff08;OA&#xff09;允许数据在没有人工干预的情况下流动。由于人工操作被排除在外&#xff0c;所以没有人为错误的风险。如今&#xff0c;办公自动化已经发展成无数的自动化和电子工具&#xff0c;改变了人们的工作方式。 办公自动化的好处 企业或多或少依…

jar包的一些事儿

在咱们日常的搬砖过程中&#xff0c;只要你涉及到Java的项目&#xff0c;就不可避免地接触到jar包。而实际开发中&#xff0c;maven等项目管理工具为我们自动地管理jar包以及相关的依赖&#xff0c;让jar包的调用看起来如黑盒一般"密不透风"。今天&#xff0c;让我们…

做音视频开发要掌握哪些知识?

最近有读者留言&#xff0c;说“想转行音视频开发&#xff0c;怎么做”&#xff0c;正巧&#xff0c;前几天我还在某乎上&#xff0c;看到有人在问音视频的学习资料&#xff0c;还是个大一的学生。 想说一句&#xff1a;真有眼光。 如今这个时代&#xff0c;想赚钱&#xff0c;…

前端开发——HTML5新增加的表单属性

1.formactiom属性 对于<input type"submit">、<button type"submit"></button>、<input type"image">元素&#xff0c;都可以指定formcation属性&#xff0c;该属性可以提交到不同的URL。 代码如下&#xff1a; <f…

自动化平台测试开发方案(详解自动化平台开发)

目录&#xff1a;导读 前言 自动化平台开发方案自动化平台开发 功能需求 技术知识点 技术知识点如表所示 自动化平台开发技术栈如图所示。 开发时间计划 投资回报率可视化 后期优化计划 登录功能实现 退出功能实现 使用Django 内置用户认证退出函数logout。 权限功…

Word控件Spire.Doc 【图像形状】教程(4) 用 C# 中的文本替换 Word 中的图像

Spire.Doc for .NET是一款专门对 Word 文档进行操作的 .NET 类库。在于帮助开发人员无需安装 Microsoft Word情况下&#xff0c;轻松快捷高效地创建、编辑、转换和打印 Microsoft Word 文档。拥有近10年专业开发经验Spire系列办公文档开发工具&#xff0c;专注于创建、编辑、转…

元宇宙|世界人工智能大会之元宇宙论坛:设计篇

Hello&#xff0c;大家好~ 这里是壹脑云科研圈&#xff0c;我是鲤鱼~ 世界人工智能大会&#xff08;WAIC&#xff09;由国家发展和改革委员会、工业和信息化部、科学技术部、国家互联网信息办公室、中国科学院、中国工程院、中国科学技术协会和上海市人民政府共同主办。 大会…

宝宝喝奶粉过敏怎么办?

为了确保喂养过程安全&#xff0c;我们仍然需要首先了解婴儿奶粉过敏的症状&#xff0c;母亲利用这些基本症状来判断婴儿是否对奶粉过敏&#xff0c;以便及时发现婴儿奶粉过敏&#xff0c;找到相应的策略。婴儿奶粉过敏婴儿奶粉过敏&#xff0c;是指婴儿喝配方奶粉后&#xff0…

【STL】string 类

​&#x1f320; 作者&#xff1a;阿亮joy. &#x1f386;专栏&#xff1a;《吃透西嘎嘎》 &#x1f387; 座右铭&#xff1a;每个优秀的人都有一段沉默的时光&#xff0c;那段时光是付出了很多努力却得不到结果的日子&#xff0c;我们把它叫做扎根 目录&#x1f449;为什么要…

一道面试题:JVM老年代空间担保机制

面试问题 昨天面试的时候&#xff0c;面试官问的问题&#xff1a; 什么是老年代空间担保机制&#xff1f;担保的过程是什么&#xff1f;老年代空间担保机制是谁给谁担保&#xff1f;为什么要有老年代空间担保机制&#xff1f;或者说空间担保机制的目的是什么&#xff1f;如果…

APS高级排产可视化设备任务甘特图

甘特图是评价一个高级计划排程系统的最重要指标之一。一方面企业排程结果数据量规模 大&#xff0c;表格形式显示数据非常不直观&#xff0c;必须借助甘特图进行可视化显示。另一方面&#xff0c;在甘特图上面手动调整排程结果&#xff0c;反馈生产实绩&#xff0c;也可大大简化…

为什么要用 Tair 来服务低延时场景 - 从购物车升级说起

「购物车升级」是今年双十一的重要体验提升项目&#xff0c;体现了大淘宝技术人“用技术突破消费者和商家体验天花板”的态度。这是一种敢于不断重新自我审视&#xff0c;然后做出更好选择的存在主义态度。 「体验提升」通常表现在以前需要降级的功能不降级&#xff0c;以前不…

Web3中文|元宇宙购物的兴起

来源 | techrepublic 近半数消费者接受元宇宙购物 根据UserTesting[1]最近的一项调查&#xff0c;42%的消费者打算在今年的节日季中&#xff08;holiday season&#xff1a;从感恩节到“黑五”&#xff0c;再到圣诞与新年&#xff09;进行元宇宙购物&#xff0c;其中88%的消费…