教程 ky tutorial

请求头与选项

Ky 支持在请求中设置各种选项,包括请求头、查询参数、超时、重试等,以满足不同场景需求。

设置请求头

通过 headers 选项设置自定义请求头:

javascript
import ky from 'ky';

async function fetchData() {
  const data = await ky.get('https://api.example.com/data', {
    headers: {
      'Authorization': 'Bearer YOUR_TOKEN',
      'X-Custom-Header': 'custom-value'
    }
  }).json();
  console.log(data);
}

fetchData();

`

查询参数

使用 searchParams 添加 URL 查询参数:

javascript
import ky from 'ky';

async function fetchUsers() {
  const users = await ky.get('https://api.example.com/users', {
    searchParams: { page: 1, limit: 20 }
  }).json();
  console.log(users);
}

fetchUsers();

请求体

  • JSON 数据使用 json
  • 表单数据使用 form
javascript
import ky from 'ky';

// JSON 请求
await ky.post('https://api.example.com/items', {
  json: { name: 'Item', price: 100 }
});

// 表单请求
const formData = new FormData();
formData.append('name', 'Item');
formData.append('price', '100');

await ky.post('https://api.example.com/items', { body: formData });

超时与重试

  • timeout:设置请求超时
  • retry:设置失败重试次数
javascript
import ky from 'ky';

const api = ky.create({
  timeout: 5000, // 5秒超时
  retry: 2       // 失败重试2次
});

小结

  • 请求头通过 headers 设置,可用于身份验证和自定义信息。
  • 查询参数通过 searchParams 轻松添加到 URL。
  • JSON 和 Form 数据通过 json 和 body 发送。
  • 可控制请求超时和失败重试策略,提升请求稳定性。