Giter Site home page Giter Site logo

ky-zh's Introduction

ky translate-svg

「 Ky是一个小巧典雅的基于浏览器Fetch API的HTTP客户端 」

中文 | english


校对 🀄

翻译的原文 与日期 最新更新 更多
commit ⏰ 2018 9.7 last 中文翻译

贡献

欢迎 👏 勘误/校对/更新贡献 😊 具体贡献请看

生活

help me live , live need money 💰



ky



Ky是一个小巧典雅的基于浏览器Fetch API的HTTP客户端

Build Status codecov

ky的目标是modern browsers. 对于较旧的浏览器,您需要导入并使用fetch polyfill. 对于Node.js,使用Got就好了.

1 KB (minified & gzipped)* ,一个文件,没有依赖项.

fetch更少要求

  • 简单API
  • 方法快捷方式 (ky.post())
  • 将非200状态码作为错误处理
  • 请求失败,重试
  • 可JSON化
  • 超时支持
  • 具有自定义默认值的实例

安装

$ npm install ky

用法

import ky from 'ky';

(async () => {
	const json = await ky.post('https://some-api.com', {json: {foo: true}}).json();

	console.log(json);
	//=> `{data: '🦄'}`
})();

fetch这将是大量的:

(async () => {
	class HTTPError extends Error {}

	const response = await fetch('https://sindresorhus.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: '🦄'}`
})();

API

KY (input,[options])

这个inputoptionsfetch一样, 但有些例外:

  • 默认情况下,这个credentials选项是same-origin,这也是规范中的默认值,但并非所有浏览器都已经规范化了.
  • 添加更多选项. 见下文.

返回一个Response 对象,其具有Body 方法为了方便而添加. 例如,你可以直接对Responseky.json(),而不用等待. 不像window.FetchBody方法,如果响应状态不在200...299范围内,就扔出HTTPError错误.

options

类型: Object

json

类型: Object

发送JSON的快捷方式. 用这个代替body选项. 接受一个plain的对象,将被JSON.stringify()处理,且为您设置正确的header.

ky.get(input, [options])

ky.post(input, [options])

ky.put(input, [options])

ky.patch(input, [options])

ky.head(input, [options])

ky.delete(input, [options])

options.method方法集合名称,发出请求.

retry

  • 类型: number
  • 默认: 2
  • 描述: 重试

用以下方法之一导致的网络错误或状态代码之一, 会重试失败的请求.

方法: GET PUT HEAD DELETE OPTIONS TRACE
状态码: 408 413 429 500 502 503 504

timeout

类型: number
默认: 10000

以毫秒为单位,获得响应的超时时间.

ky.extend(defaultOptions)

创建新的ky实例,自己重写部分选项.

defaultOptions

类型: Object

ky.HTTPError

暴露给instanceof做检查. 错误会有Response 对象response属性.

ky.TimeoutError

请求超时时,引发的错误.

提示

取消

Fetch (因此Ky) 具有内置的请求取消的支持,通过AbortController API.查阅更多.

例子:

import ky from 'ky';

const controller = new AbortController();
const {signal} = controller;

setTimeout(() => controller.abort(), 5000);

(async () => {
	try {
		console.log(await ky(url, {signal}).text());
	} catch (error) {
		if (error.name === 'AbortError') {
		  console.log('Fetch aborted');
		} else {
		  console.error('Fetch error:', error);
		}
	}
})();

常见问题解答

它与r2有什么不同?

看到我的答案#10.

浏览器支持

最新版本的Chrome,Firefox和Safari.

相关的

  • got-对Node.js的HTTP请求

许可证

MIT © Sindre Sorhus

ky-zh's People

Contributors

chinanf-boy avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.