Ky是一个基于Fetch API的小巧而优雅的HTTP客户端
Ky针对现代浏览器、Node.js、Bun和Deno。
它只是一个没有依赖项的小型包。
fetch的优势ky.post()).json()支持泛型并默认为unknown,而不是any)npm install ky
import ky from 'ky'; const json = await ky.post('https://example.com', {json: {foo: true}}).json(); console.log(json); //=> `{data: '🦄'}`
使 用普通的fetch,它将是:
class HTTPError extends Error {} const response = await fetch('https://example.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: '🦄'}`
如果你使用的是Deno,从URL导入Ky。例如,使用CDN:
import ky from 'https://esm.sh/ky';
input和options与fetch相同,还提供了额外的options(见下文)。
返回一个带有Body方法的Response对象,以方便使用。因此,你可以直接调用ky.get(input).json(),而不必先等待Response。当这样调用时,将根据使用的body方法设置适当的Accept头。与window.Fetch的Body方法不同,如果响应状态不在200...299范围内,这些方法将抛出HTTPError。此外,如果body为空或响应状态为204,.json()将返回空字符串,而不是因为空body而抛出解析错误。
import ky from 'ky'; const user = await ky('/api/user').json(); console.log(user);
⌨️ TypeScript: 接受一个可选的类型参数,默认为unknown,并传递给.json()的返回类型。
import ky from 'ky'; // user1是unknown类型 const user1 = await ky('/api/users/1').json(); // user2是User类型 const user2 = await ky<User>('/api/users/2').json(); // user3是User类型 const user3 = await ky('/api/users/3').json<User>(); console.log([user1, user2, user3]);
将options.method设置为方法名并发起请求。
⌨️ TypeScript: 接受一个可选的类型参数,用于JSON响应(参见ky())。
类型:string | URL | Request
与fetch input相同。
当使用Request实例作为input时,任何改变URL的选项(如prefixUrl)将被忽略。
类型:object
与fetch options相同,外加以下额外选项:
类型:string
默认值:'get'
用于发起请求的HTTP方法。
内部会将标准方法(GET、POST、PUT、PATCH、HEAD和DELETE)转为大写,以避免由于大小写敏感性导致的服务器错误。
类型:object和JSON.stringify()接受的任何其他值
发送JSON的快捷方式。使用此选项代替body选项。接受任何普通对象或值,这些值将被JSON.stringify()处理并在正文中发送,同时设置正确的头部。
类型:string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams
默认值:''
要包含在请求URL中的搜索参数。设置此项将覆盖输入URL中的所有现有搜索参数。
接受URLSearchParams()支持的任何值。
类型:string | URL
在发起请求时,要预先添加到input URL的前缀。它可以是任何有效的URL,相对或绝对。末尾的斜杠/是可选的,如果需要,在与input连接时会自动添加。仅当input是字符串时生效。使用此选项时,input参数不能以斜杠/开头。
在使用ky.extend()创建特定领域的Ky实例时非常有用。
import ky from 'ky'; // 在 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'
注意:
prefixUrl 和 input 后,结果会根据页面的基础 URL(如果有)进行解析。input 中有前导斜杠,以确保一致性并避免对 input URL 处理方式产生混淆。因为使用 prefixUrl 时,input 不会遵循正常的 URL 解析规则,这改变了前导斜杠的含义。类型:object | number
默认值:
limit:2methods:get put head delete options tracestatusCodes:408 413 429 500 502 503 504afterStatusCodes:413、429、503maxRetryAfter:undefinedbackoffLimit:undefineddelay:attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000一个对象,表示最大重试次数、允许的方法、允许的状态码、允许使用 Retry-After 时间的状态码,以及最大 Retry-After 时间的 limit、methods、statusCodes、afterStatusCodes 和 maxRetryAfter 字段。
如果 retry 是一个数字,它将被用作 limit,其他默认值保持不变。
如果响应提供的 HTTP 状态包含在 afterStatusCodes 中,Ky 将等待 Retry-After 头部给出的日期、超时或时间戳过去后再重试请求。如果缺少 Retry-After,则使用非标准的 RateLimit-Reset 头部作为备用。如果提供的状态码不在列表中,将忽略 Retry-After 头部。
如果 maxRetryAfter 设置为 undefined,它将使用 options.timeout。如果 Retry-After 头部大于 maxRetryAfter