Fetch基于TS的简单封装

1,731 阅读1分钟

JS 提供了 fetch 方法来请求数据,我们在这里对它进行简单的 TS 封装

封装fetch

image.png

  • fetch
const BASE_URL =
  process.env.NODE_ENV == 'production' ? '' : 'http://localhost:3000/api'

type configType = {
  url: string
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data: any
}

class SxRequest {
  baseURL: string

  constructor(config: { baseURL: string }) {
    this.baseURL = config.baseURL
  }

  async request<T = any>(config: configType) {
    // fetch中GET方法没有请求体 需要拼接到url中 参数直接拼接
    const fetchURL = this.baseURL + config.url

    // 如果是POST 把data传递给body
    const fetchConfig: RequestInit =
      config.method === 'POST'
        ? {
            method: config.method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(config.data)
          }
        : {
            method: config.method
          }

    // 获取fetch的数据并返回
    const res = await fetch(fetchURL, fetchConfig)
    const data: T = await res.json()
    return data
  }

  get<T1 = any, T2 = any>(url: string, data?: T2) {
    return this.request<T1>({ url, method: 'GET', data })
  }

  post<T1 = any, T2 = any>(url: string, data?: T2) {
    return this.request<T1>({ url: url, method: 'POST', data })
  }
}

export default new SxRequest({
  baseURL: BASE_URL
})

todo

import { ITodo, ResType } from '@/type'
import sxRequest from '../index'

// 查询todo列表
export const getTodoList = () => {
  return sxRequest.get<ResType<ITodo[]>>('/api/todo/list')
}

// 创建todo
export const createTodo = (content: string) => {
  return sxRequest.post<ResType<ITodo>, { content: string }>(
    '/api/todo/create',
    {
      content
    }
  )
}

// 更新todo
export const updateTodo = (todo: ITodo) => {
  return sxRequest.post<ResType<ITodo>, ITodo>('/api/todo/update', todo)
}

// 删除todo
export const deleteTodo = (id: string) => {
  return sxRequest.post<ResType<ITodo>, { id: string }>('/api/todo/delete', {
    id
  })
}
  • 使用
// 网络请求
const res = await getTodoList()