CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
readme.md803 linesDownload Raw Back to ky
1<div align="center">2	<br>3	<div>4		<img width="600" height="600" src="media/logo.svg" alt="ky">5	</div>6	<br>7	<br>8	<p>9		<p>10			<sup>11				Sindre's open source work is supported by the community.<br>Special thanks to:12			</sup>13		</p>14		<br>15		<br>16		<a href="https://logto.io/?ref=sindre">17			<div>18				<picture>19					<source width="200" media="(prefers-color-scheme: dark)" srcset="https://sindresorhus.com/assets/thanks/logto-logo-dark.svg?x">20					<source width="200" media="(prefers-color-scheme: light)" srcset="https://sindresorhus.com/assets/thanks/logto-logo-light.svg?x">21					<img width="200" src="https://sindresorhus.com/assets/thanks/logto-logo-light.svg?x" alt="Logto logo">22				</picture>23			</div>24			<b>The better identity infrastructure for developers</b>25			<div>26				<sup>Logto is an open-source Auth0 alternative designed for every app.</sup>27			</div>28		</a>29	</p>30	<br>31	<br>32	<br>33	<br>34	<br>35	<br>36	<br>37	<br>38</div>39 40> Ky is a tiny and elegant HTTP client based on the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)41 42[![Coverage Status](https://codecov.io/gh/sindresorhus/ky/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/ky)43[![](https://badgen.net/bundlephobia/minzip/ky)](https://bundlephobia.com/result?p=ky)44 45Ky targets [modern browsers](#browser-support), Node.js, Bun, and Deno.46 47It's just a tiny package with no dependencies.48 49## Benefits over plain `fetch`50 51- Simpler API52- Method shortcuts (`ky.post()`)53- Treats non-2xx status codes as errors (after redirects)54- Retries failed requests55- JSON option56- Timeout support57- URL prefix option58- Instances with custom defaults59- Hooks60- TypeScript niceties (e.g. `.json()` supports generics and defaults to `unknown`, not `any`)61 62## Install63 64```sh65npm install ky66```67 68###### CDN69 70- [jsdelivr](https://cdn.jsdelivr.net/npm/ky/+esm)71- [unpkg](https://unpkg.com/ky)72- [esm.sh](https://esm.sh/ky)73 74## Usage75 76```js77import ky from 'ky';78 79const json = await ky.post('https://example.com', {json: {foo: true}}).json();80 81console.log(json);82//=> {data: '🦄'}83```84 85With plain `fetch`, it would be:86 87```js88class HTTPError extends Error {}89 90const response = await fetch('https://example.com', {91	method: 'POST',92	body: JSON.stringify({foo: true}),93	headers: {94		'content-type': 'application/json'95	}96});97 98if (!response.ok) {99	throw new HTTPError(`Fetch error: ${response.statusText}`);100}101 102const json = await response.json();103 104console.log(json);105//=> {data: '🦄'}106```107 108If you are using [Deno](https://github.com/denoland/deno), import Ky from a URL. For example, using a CDN:109 110```js111import ky from 'https://esm.sh/ky';112```113 114## API115 116### ky(input, options?)117 118The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with additional `options` available (see below).119 120Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with [`Body` methods](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#body) 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.121 122```js123import ky from 'ky';124 125const user = await ky('/api/user').json();126 127console.log(user);128```129 130⌨️ **TypeScript:** Accepts an optional [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html), which defaults to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown), and is passed through to the return type of `.json()`.131 132```ts133import ky from 'ky';134 135// user1 is unknown136const user1 = await ky('/api/users/1').json();137// user2 is a User138const user2 = await ky<User>('/api/users/2').json();139// user3 is a User140const user3 = await ky('/api/users/3').json<User>();141 142console.log([user1, user2, user3]);143```144 145### ky.get(input, options?)146### ky.post(input, options?)147### ky.put(input, options?)148### ky.patch(input, options?)149### ky.head(input, options?)150### ky.delete(input, options?)151 152Sets `options.method` to the method name and makes a request.153 154⌨️ **TypeScript:** Accepts an optional type parameter for use with JSON responses (see [`ky()`](#kyinput-options)).155 156#### input157 158Type: `string` | `URL` | `Request`159 160Same as [`fetch` input](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#input).161 162When using a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance as `input`, any URL altering options (such as `prefixUrl`) will be ignored.163 164#### options165 166Type: `object`167 168Same as [`fetch` options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options), plus the following additional options:169 170##### method171 172Type: `string`\173Default: `'get'`174 175HTTP method used to make the request.176 177Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.178 179##### json180 181Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)182 183Shortcut for sending JSON. Use this instead of the `body` option. Accepts any plain object or value, which will be `JSON.stringify()`'d and sent in the body with the correct header set.184 185##### searchParams186 187Type: `string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams`\188Default: `''`189 190Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.191 192Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).193 194##### prefixUrl195 196Type: `string | URL`197 198A 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.199 200Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky-instances.201 202```js203import ky from 'ky';204 205// On https://example.com206 207const response = await ky('unicorn', {prefixUrl: '/api'});208//=> 'https://example.com/api/unicorn'209 210const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});211//=> 'https://cats.com/unicorn'212```213 214Notes:215 - After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).216 - Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `prefixUrl` is being used, which changes the meaning of a leading slash.217 218##### retry219 220Type: `object | number`\221Default:222- `limit`: `2`223- `methods`: `get` `put` `head` `delete` `options` `trace`224- `statusCodes`: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)225- `afterStatusCodes`: [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413), [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429), [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503)226- `maxRetryAfter`: `undefined`227- `backoffLimit`: `undefined`228- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`229 230An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.231 232If `retry` is a number, it will be used as `limit` and other defaults will remain in place.233 234If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.235 236If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.237 238The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.239To clamp the delay, set `backoffLimit` to 1000, for example.240By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.241 242The `delay` option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at `1`.243 244Retries are not triggered following a [timeout](#timeout).245 246```js247import ky from 'ky';248 249const json = await ky('https://example.com', {250	retry: {251		limit: 10,252		methods: ['get'],253		statusCodes: [413],254		backoffLimit: 3000255	}256}).json();257```258 259##### timeout260 261Type: `number | false`\262Default: `10000`263 264Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647.265If set to `false`, there will be no timeout.266 267##### hooks268 269Type: `object<string, Function[]>`\270Default: `{beforeRequest: [], beforeRetry: [], afterResponse: []}`271 272Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.273 274###### hooks.beforeRequest275 276Type: `Function[]`\277Default: `[]`278 279This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives `request` and `options` as arguments. You could, for example, modify the `request.headers` here.280 281The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a request or response from this hook is that any remaining `beforeRequest` hooks will be skipped, so you may want to only return them from the last hook.282 283```js284import ky from 'ky';285 286const api = ky.extend({287	hooks: {288		beforeRequest: [289			request => {290				request.headers.set('X-Requested-With', 'ky');291			}292		]293	}294});295 296const response = await api.get('https://example.com/api/users');297```298 299###### hooks.beforeRetry300 301Type: `Function[]`\302Default: `[]`303 304This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.305 306If the request received a response, the error will be of type `HTTPError` and the `Response` object will be available at `error.response`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of `HTTPError`.307 308You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).309 310```js311import ky from 'ky';312 313const response = await ky('https://example.com', {314	hooks: {315		beforeRetry: [316			async ({request, options, error, retryCount}) => {317				const token = await ky('https://example.com/refresh-token');318				request.headers.set('Authorization', `token ${token}`);319			}320		]321	}322});323```324 325###### hooks.beforeError326 327Type: `Function[]`\328Default: `[]`329 330This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`.331 332```js333import ky from 'ky';334 335await ky('https://example.com', {336	hooks: {337		beforeError: [338			error => {339				const {response} = error;340				if (response && response.body) {341					error.name = 'GitHubError';342					error.message = `${response.body.message} (${response.status})`;343				}344 345				return error;346			}347		]348	}349});350```351 352###### hooks.afterResponse353 354Type: `Function[]`\355Default: `[]`356 357This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).358 359```js360import ky from 'ky';361 362const response = await ky('https://example.com', {363	hooks: {364		afterResponse: [365			(_request, _options, response) => {366				// You could do something with the response, for example, logging.367				log(response);368 369				// Or return a `Response` instance to overwrite the response.370				return new Response('A different response', {status: 200});371			},372 373			// Or retry with a fresh token on a 403 error374			async (request, options, response) => {375				if (response.status === 403) {376					// Get a fresh token377					const token = await ky('https://example.com/token').text();378 379					// Retry with the token380					request.headers.set('Authorization', `token ${token}`);381 382					return ky(request);383				}384			}385		]386	}387});388```389 390##### throwHttpErrors391 392Type: `boolean`\393Default: `true`394 395Throw an `HTTPError` when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the [`redirect`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) option to `'manual'`.396 397Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.398 399Note: If `false`, error responses are considered successful and the request will not be retried.400 401##### onDownloadProgress402 403Type: `Function`404 405Download progress event handler.406 407The function receives these arguments:408- `progress` is an object with the these properties:409- - `percent` is a number between 0 and 1 representing the progress percentage.410- - `transferredBytes` is the number of bytes transferred so far.411- - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.412- `chunk` is an instance of `Uint8Array` containing the data that was sent. Note: It's empty for the first call.413 414```js415import ky from 'ky';416 417const response = await ky('https://example.com', {418	onDownloadProgress: (progress, chunk) => {419		// Example output:420		// `0% - 0 of 1271 bytes`421		// `100% - 1271 of 1271 bytes`422		console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);423	}424});425```426 427##### onUploadProgress428 429Type: `Function`430 431Upload progress event handler.432 433The function receives these arguments:434- `progress` is an object with the these properties:435- - `percent` is a number between 0 and 1 representing the progress percentage.436- - `transferredBytes` is the number of bytes transferred so far.437- - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.438- `chunk` is an instance of `Uint8Array` containing the data that was sent. Note: It's empty for the last call.439 440```js441import ky from 'ky';442 443const response = await ky.post('https://example.com/upload', {444	body: largeFile,445	onUploadProgress: (progress, chunk) => {446		// Example output:447		// `0% - 0 of 1271 bytes`448		// `100% - 1271 of 1271 bytes`449		console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);450	}451});452```453 454##### parseJson455 456Type: `Function`\457Default: `JSON.parse()`458 459User-defined JSON-parsing function.460 461Use-cases:4621. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.4632. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).464 465```js466import ky from 'ky';467import bourne from '@hapijs/bourne';468 469const json = await ky('https://example.com', {470	parseJson: text => bourne(text)471}).json();472```473 474##### stringifyJson475 476Type: `Function`\477Default: `JSON.stringify()`478 479User-defined JSON-stringifying function.480 481Use-cases:4821. Stringify JSON with a custom `replacer` function.483 484```js485import ky from 'ky';486import {DateTime} from 'luxon';487 488const json = await ky('https://example.com', {489	stringifyJson: data => JSON.stringify(data, (key, value) => {490		if (key.endsWith('_at')) {491			return DateTime.fromISO(value).toSeconds();492		}493 494		return value;495	})496}).json();497```498 499##### fetch500 501Type: `Function`\502Default: `fetch`503 504User-defined `fetch` function.505Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.506 507Use-cases:5081. Use custom `fetch` implementations like [`isomorphic-unfetch`](https://www.npmjs.com/package/isomorphic-unfetch).5092. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).510 511```js512import ky from 'ky';513import fetch from 'isomorphic-unfetch';514 515const json = await ky('https://example.com', {fetch}).json();516```517 518### ky.extend(defaultOptions)519 520Create a new `ky` instance with some defaults overridden with your own.521 522In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.523 524You can pass headers as a `Headers` instance or a plain object.525 526You can remove a header with `.extend()` by passing the header with an `undefined` value.527Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.528 529Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.530 531```js532import ky from 'ky';533 534const url = 'https://sindresorhus.com';535 536const original = ky.create({537	headers: {538		rainbow: 'rainbow',539		unicorn: 'unicorn'540	},541	hooks: {542		beforeRequest: [ () => console.log('before 1') ],543		afterResponse: [ () => console.log('after 1') ],544	},545});546 547const extended = original.extend({548	headers: {549		rainbow: undefined550	},551	hooks: {552		beforeRequest: undefined,553		afterResponse: [ () => console.log('after 2') ],554	}555});556 557const response = await extended(url).json();558//=> after 1559//=> after 2560 561console.log('rainbow' in response);562//=> false563 564console.log('unicorn' in response);565//=> true566```567 568You can also refer to parent defaults by providing a function to `.extend()`.569 570```js571import ky from 'ky';572 573const api = ky.create({prefixUrl: 'https://example.com/api'});574 575const usersApi = api.extend((options) => ({prefixUrl: `${options.prefixUrl}/users`}));576 577const response = await usersApi.get('123');578//=> 'https://example.com/api/users/123'579 580const response = await api.get('version');581//=> 'https://example.com/api/version'582```583 584### ky.create(defaultOptions)585 586Create a new Ky instance with complete new defaults.587 588```js589import ky from 'ky';590 591// On https://my-site.com592 593const api = ky.create({prefixUrl: 'https://example.com/api'});594 595const response = await api.get('users/123');596//=> 'https://example.com/api/users/123'597 598const response = await api.get('/status', {prefixUrl: ''});599//=> 'https://my-site.com/status'600```601 602#### defaultOptions603 604Type: `object`605 606### ky.stop607 608A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.609 610Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.611 612A valid use-case for `ky.stop` is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.613 614```js615import ky from 'ky';616 617const options = {618	hooks: {619		beforeRetry: [620			async ({request, options, error, retryCount}) => {621				const shouldStopRetry = await ky('https://example.com/api');622				if (shouldStopRetry) {623					return ky.stop;624				}625			}626		]627	}628};629 630// Note that response will be `undefined` in case `ky.stop` is returned.631const response = await ky.post('https://example.com', options);632 633// Using `.text()` or other body methods is not supported.634const text = await ky('https://example.com', options).text();635```636 637### HTTPError638 639Exposed for `instanceof` checks. The error has a `response` property with the [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response), `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request), and `options` property with normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request).640 641Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of HTTPError and will not contain a `response` property.642 643If you need to read the actual response when an `HTTPError` has occurred, call the respective parser method on the response object. For example:644 645```js646try {647	await ky('https://example.com').json();648} catch (error) {649	if (error.name === 'HTTPError') {650		const errorJson = await error.response.json();651	}652}653```654 655⌨️ **TypeScript:** Accepts an optional [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html), which defaults to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown), and is passed through to the return type of `error.response.json()`.656 657### TimeoutError658 659The error thrown when the request times out. It has a `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request).660 661## Tips662 663### Sending form data664 665Sending form data in Ky is identical to `fetch`. Just pass a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instance to the `body` option. The `Content-Type` header will be automatically set to `multipart/form-data`.666 667```js668import ky from 'ky';669 670// `multipart/form-data`671const formData = new FormData();672formData.append('food', 'fries');673formData.append('drink', 'icetea');674 675const response = await ky.post(url, {body: formData});676```677 678If you want to send the data in `application/x-www-form-urlencoded` format, you will need to encode the data with [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).679 680```js681import ky from 'ky';682 683// `application/x-www-form-urlencoded`684const searchParams = new URLSearchParams();685searchParams.set('food', 'fries');686searchParams.set('drink', 'icetea');687 688const response = await ky.post(url, {body: searchParams});689```690 691### Setting a custom `Content-Type`692 693Ky automatically sets an appropriate [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such as `application/x-amz-json-1.1`. Using the `headers` option, you can manually override the content type.694 695```js696import ky from 'ky';697 698const json = await ky.post('https://example.com', {699	headers: {700		'content-type': 'application/json'701	},702	json: {703		foo: true704	},705}).json();706 707console.log(json);708//=> {data: '🦄'}709```710 711### Cancellation712 713Fetch (and hence Ky) has built-in support for request cancellation through the [`AbortController` API](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). [Read more.](https://developers.google.com/web/updates/2017/09/abortable-fetch)714 715Example:716 717```js718import ky from 'ky';719 720const controller = new AbortController();721const {signal} = controller;722 723setTimeout(() => {724	controller.abort();725}, 5000);726 727try {728	console.log(await ky(url, {signal}).text());729} catch (error) {730	if (error.name === 'AbortError') {731		console.log('Fetch aborted');732	} else {733		console.error('Fetch error:', error);734	}735}736```737 738## FAQ739 740#### How do I use this in Node.js?741 742Node.js 18 and later supports `fetch` natively, so you can just use this package directly.743 744#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?745 746Same as above.747 748#### How do I test a browser library that uses this?749 750Either use a test runner that can run in the browser, like Mocha, or use [AVA](https://avajs.dev) with `ky-universal`. [Read more.](https://github.com/sindresorhus/ky-universal#faq)751 752#### How do I use this without a bundler like Webpack?753 754Make 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.755 756```html757<script type="module">758import ky from 'https://unpkg.com/ky/distribution/index.js';759 760const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();761 762console.log(json.title);763//=> 'delectus aut autem'764</script>765```766 767#### How is it different from [`got`](https://github.com/sindresorhus/got)768 769See my answer [here](https://twitter.com/sindresorhus/status/1037406558945042432). Got is maintained by the same people as Ky.770 771#### How is it different from [`axios`](https://github.com/axios/axios)?772 773See my answer [here](https://twitter.com/sindresorhus/status/1037763588826398720).774 775#### How is it different from [`r2`](https://github.com/mikeal/r2)?776 777See my answer in [#10](https://github.com/sindresorhus/ky/issues/10).778 779#### What does `ky` mean?780 781It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:782 783> A form of text-able slang, KY is an abbreviation for 空気読めない (kuuki yomenai), which literally translates into “cannot read the air.” It's a phrase applied to someone who misses the implied meaning.784 785## Browser support786 787The latest version of Chrome, Firefox, and Safari.788 789## Node.js support790 791Node.js 18 and later.792 793## Related794 795- [fetch-extras](https://github.com/sindresorhus/fetch-extras) - Useful utilities for working with Fetch796- [ky-hooks-change-case](https://github.com/alice-health/ky-hooks-change-case) - Ky hooks to modify cases on requests and responses of objects797 798## Maintainers799 800- [Sindre Sorhus](https://github.com/sindresorhus)801- [Seth Holladay](https://github.com/sholladay)802- [Szymon Marczak](https://github.com/szmarczak)803 
basant307/AI_Governance_Project · CoolFace