Skip to content

快速开始

安装 Alpha

v4 alpha 已发布到 npm。使用 alpha dist-tag 安装:

sh
npm install luch-request@alpha

不带 @alphanpm install luch-request 会安装 npm latest 通道对应的稳定版本。

ESM only

v4 只提供 ESM,不再提供默认导出、CommonJS 或 UMD。使用方构建工具需要能消费 ESM 与 ES2017 语法。

创建实例

ts
import { createLuchRequest } from 'luch-request'

const http = createLuchRequest({
  baseURL: 'https://api.example.com',
  timeout: 10_000,
  header: {
    Accept: 'application/json'
  }
})

不同实例的默认配置和 interceptor 不共享。没有配置 method 时,普通 request() 默认使用 GET;快捷方法使用自身固定 method。

发出请求

ts
interface User {
  id: number
  name: string
}

interface UserListParams {
  page: number
  pageSize: number
}

const response = await http.get<User[], UserListParams>('/users', {
  params: {
    page: 1,
    pageSize: 20
  }
})

console.log(response.data[0].name)
console.log(response.statusCode)
console.log(response.config.fullURL)

第一个泛型描述 response.data,第二个泛型描述查询参数。只关心响应类型时, 写成 http.get<User[]>('/users', { params }) 即可。

处理错误

ts
import {
  isLuchRequestError,
  LuchRequestError
} from 'luch-request'

try {
  await http.get<User>('/users/1')
} catch (error) {
  if (!isLuchRequestError(error)) {
    throw error
  }

  if (error.code === LuchRequestError.ERR_CANCELED) {
    console.log('请求已取消')
  }

  if (error.response) {
    console.log('已经取得响应上下文', error.response.statusCode)
  }
}

业务判断应使用 error.code,不要匹配 messageerror.response 的准确含义和 服务端到达判断见错误处理

下一步

v4 处于 Alpha 阶段,公共 API 仍可能调整。