@ymir-labs/http

0.0.40 • Public • Published

@ymir-labs/http

Axios 轻量级封装,提供易用的Ajax方法。

安装

pnpm install @ymir-labs/http

基本使用

发送GET请求

import { http } from '@ymir-labs/http'

const userId = 'user-123'
const deptId = 'dept-1'
const user = await http.get('/user-info', { params: { userId, deptId } })

以上代码发送 /user-info?userId=user-123&deptId=dept-1 请求。user 是接口返回的JSON数据对象。例如返回以下JSON数据:

{
  "userName": "张三",
  "deptName": "A部门"
}

那么通过以下方式就可以获取数据:

console.log(`${user.userName}, ${user.deptName}`)

推荐指定响应数据类型,如下所示:

import { http } from '@ymir-labs/http'

/**
 * 用户信息
 */
interface User {
  /**
   * 用户id
   */
  userId: string
  /**
   * 用户名称
   */
  userName: string
  /**
   * 部门id
   */
  deptId: string
  /**
   * 部门名称
   */
  deptName: string
}

const user = http.get<User>('/user-info', { params: { userId, deptId }})

使用POST/PUT提交数据

import { http } from '@ymir-labs/http'

interface TodoItem {
  id: string
  title: string
  status: 'todo' | 'done'
}

const todo = { title: '待办事项1', status: 'todo' }
const addedTodo = await http.post<TodoItem>('/todos', todo)

const updatingTodo = { ...addedTodo, status: 'done' }
const updatedTodo = await http.put<TodoItem>(`/todos/${updatingTodo.id}`, updatingTodo)

发送DELETE请求

const todoId = 'todo-1'
const result = await http.delete(`/todos/${todoId}`)

http 数据传递

目前有三种数据传递方式:

  • 请求参数
  • 路径参数
  • 请求体

请求参数

请求参数一般用于传递查询参数、过滤条件,也会在更新、删除请求中用于传递一些独立的参数。如:

http://url/todos?page=3&size=15

上面的 url 中,有两个请求参数,即pagesize,分别是315.对应如下代码:

import http from '@ymir-libs/http'

const page = 3
const size = 15
const todos = await http.get('/todos', { params: { page, size }})

在 POST、PUT、DELETE 时传递请求参数时,要格外小心,应该以如下的方式传递请求参数:

import http from '@ymir-libs/http'

// 请求参数
const id = 'xxx'
const jsbm = '部门1,部门2'

// 需要提交的数据
const data = {}
const result = await http.post('/demo', data, {
  params: { id, jsbm }
})

如果需要传递一组数据,则 http 会做以下序列化:

const ids = ['1', '2', '3']
await http.get('/demo', { params: { ids }})

发送的请求链接为:/demo?ids=1&ids=2&ids=3

路径参数

路径参数一般用于在 url 路径部分添加资源 id,如下所示:

import http from '@ymir-libs/http'

const todoId = 'todo-1'
await http.put(`/todos/${todoId}`)
await http.delete(`/todos/${todoId}`)

请求体

我们在实际业务场景中,频繁使用一种请求体格式,即application/jsonhttp已经做了 json 的自动处理,只需要在postput方法的第二个参数传递一个对象,http就会自动将此 js 对象转换成 JSON 字符串传递给后端。

import http from '@ymir-libs/http'

const requestBody = { userName: 'jacking' }
const result = await http.post(url, requestBody)

谨记: 在做实际开发时,一定要仔细阅读相关 API 约束,确定需要传递参数的数据结构。

上传文件

提交表单中的文件

import http from '@ymir-libs/http'

const file = document.getElementById('file').files[0]
const result = await http.sendFile('/apis/files', file)

发送的是POST请求。

提交blob

import http from '@ymir-libs/http'

const blob = new Blob(["Hello, World!"], { type: 'text/plain' })
const result = await http.sendFile('/apis/files', blob)

提交file

有一些file不是由表单产生的,而是由其他方式产生的。例如:

import http from '@ymir-libs/http'

const blob = new Blob(["Hello, World!"], { type: 'text/plain' })
const file = new File([blob], 'demo.txt', { type: 'text/plain' })
const result = await http.sendFile('/apis/files', file)

上传文件时传递其他信息

上传时添加额外数据:

import http from '@ymir-libs/http'

http.sendFile('/apis/files', file, {
  // 上传时传递的额外数据
  data: {
    userId: '123',
    userName: 'zhangsan',
  },
})

查看文件上传进度

import http from '@ymir-libs/http'

const onUploadProgress = (progressEvent: ProgressEvent) => {
  console.log(
    `上传进度:${((progressEvent.loaded / progressEvent.total) * 100) | 0}%`,
  )
}

await sendFile(url, files, {
  onUploadProgress,
})

错误处理

捕获错误响应

响应码为2xx的均认为是响应成功,其他的响应码均认为是错误,会抛出错误,如下所示:

import { isHttpError, errorMessage } from '@ymir-libs/http'

try {
  const result = await http.post('/demo')
} catch (error) {
  if (isHttpError(error)) {
    console.log(`http错误,响应状态码:${error.statusCode},响应内容:${error.}`)
  }
}

监听响应错误

import http, { isHttpError } from '@ymir-libs/http'

const removeListener = http.onFailure(error => {
  if (isHttpError(error) && error.response.status === 401) {
    console.log('未登录,跳转到登录页')
  }
  throw error
})

// 取消错误监听
removeListener()

输出错误信息

import { isHttpError, errorMessage } from '@ymir-libs/http'

try {
  const result = await http.post('/demo')
} catch (error) {
  console.log(errorMessage(error, '失败啦'))
}

响应拦截器

import http from '@ymir-libs/http'

const removeListener = http.onResponse((response) => {
  console.log(`接收到响应:${response.data}`)
  return response
})

// 取消响应监听
removeListener()

Package Sidebar

Install

npm i @ymir-labs/http

Weekly Downloads

324

Version

0.0.40

License

MIT

Unpacked Size

14.8 kB

Total Files

8

Last publish

Collaborators

  • china_loubin
  • jackingliu
  • mikasa33