Scott

react api层demo a year ago

react
2640个字符
共有102人围观

在做react开发时,http请求建议单独封装,这样不仅利于阅读,也更方便维护

先展示下我个人的目录结构(不喜勿喷):

如上解释说明:

  • axios.tsx: 是对axios的封装,这样你不必每次都写baseURL
  • general_types.tsx: 放置的是HTTP请求需要用到的通用type,如搜索通常会用到页码和关键字2个字段,封装之后,大家都可以用,而不用单独定义
  • endpoint: 各个table对接口的封装

来看下示例:

endpoint/axios.tsx:

import axios from "axios";
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()

//axios实例
const myAxiosInstance = axios.create();
//https://axios-http.com/docs/interceptors
// Add a request interceptor
myAxiosInstance.interceptors.request.use(function (config) {
    config.baseURL = 'http://127.0.0.1:9998/api/v1'
    config.timeout=2000
    // Do something before request is sent
    return config;
  }, function (error) {
    // console.log("request error:",error)
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
myAxiosInstance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // console.log("response:",response)
    return response;
  }, function (error) {
    // console.log("response error:",error)
    if (error.message==="Request failed with status code 401"){
        // console.log("401")
        navigate('/')
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

export default myAxiosInstance

endpoint/general_types.tsx:

interface SearchInfo {
    page?:number; //当前页
    keyword?:string;//关键字
}

endpoint/brand.tsx:

import myAxiosInstance from "./utils/axios"

interface BrandCreateInfo {
    name?:string;
    full_name?:string;
    is_next_year?:boolean;
}

interface BrandUpdatedInfo extends BrandCreateInfo{
    id:number;
}

const brandAPI = {
    createBand: (bandCreateInfo:BrandCreateInfo)=> myAxiosInstance.post("/brand/create",bandCreateInfo),
    updateBrand: (brandUpdatedInfo:BrandUpdatedInfo)=> myAxiosInstance.post("/brand/updateById",brandUpdatedInfo),
    getOnePageBrands: (brandSearchInfo:SearchInfo) => myAxiosInstance.get(`/brand/page?page=${brandSearchInfo.page}&keyword=${brandSearchInfo.keyword}`,{}),
    getBrandById: (id:number) => myAxiosInstance.get(`/brand/getById?id=${id}`,{}),
    checkBrandNameIfRepeatedWhenCreating: (name:string) => myAxiosInstance.post("/brand/create/name_repeated",{name}),
    checkBrandNameIfRepeatedWhenUpdating: (name:string, id:number) => myAxiosInstance.post("/brand/update/name_repeated",{name,id})
}

export default brandAPI