现代化框架API配置方式记录,持续更新

272 阅读2分钟

API俩种配置记录

上一篇:React总结来说(通信/redux/路由/钩子函数/三大解决逻辑共享方案(组件))

方式一

  • http

                 import axios from "axios";
    
                  let defaultConfig = {
                    timeout: 3000,
                    baseURL: "xxxxxxxxxxxx"
                  };
    
                  //axios,初始化
                  let instance: any = axios;
    
                  //定义一个类
                  class Axios {
                    //构造函数,创建一个类
                    constructor(props: any) {
                      //props是undefind或者不是object就使用默认配置
                      if (props && typeof props == "object") {
                        instance = axios.create(props);
                      } else {
                        instance = axios.create(defaultConfig);
                      }
    
                      //请求拦截器
                      instance.interceptors.request.use(
                        (config: any) => {
                          //直接发送请求,不做任何处理
                          return config;
                        },
                        (error: any) => {
                          console.log(error);
                          return Promise.reject(error);
                        }
                      );
    
                      //响应拦截器
                      instance.interceptors.response.use(
                        (response: any) => {
                          //直接返回请求结果,不做任何处理
                          return response.data;
                        },
                        (error: any) => {
                          console.log(error);
                          return Promise.reject(error);
                        }
                      );
                    }
    
                    //send方法
                    send(params: any) {
                      console.log(params);
                      if (!params || typeof params != "object") {
                        throw new Error("params is undefined or not an object");
                      }
                      if (params.method == "get") {
                        return get(params.url);
                      } else if (params.method == "post") {
                        return post(params.url);
                      } else if (params.method == "put") {
                        return put(params.url);
                      } else if (params.method == "patch") {
                        return patch(params.url);
                      } else if (params.method == "delete") {
                        return deletes(params.url);
                      }
                    }
                  }
    
                  //异步get请求类型的方法
                  async function get(url: string) {
                    try {
                      let response = await instance.get(url);
                      return response;
                    } catch (e) {
                      console.log(e);
                    }
                  }
                  //异步post请求类型的方法
                  async function post(url: string) {
                    try {
                      let response = await instance.post(url);
                      //return callback(response)
                      return response;
                    } catch (e) {
                      console.log(e);
                    }
                  }
                  //异步delete请求类型的方法
                  async function deletes(url: string) {
                    try {
                      let response = await instance.delete(url);
                      //return callback(response)
                      return response;
                    } catch (e) {
                      console.log(e);
                    }
                  }
                  //异步put请求类型的方法
                  async function put(url: string) {
                    try {
                      let response = await instance.put(url);
                      //return callback(response)
                      return response;
                    } catch (e) {
                      console.log(e);
                    }
                  }
                  //异步patch请求类型的方法
                  async function patch(url: string) {
                    try {
                      let response = await instance.patch(url);
                      //return callback(response)
                      return response;
                    } catch (e) {
                      console.log(e);
                    }
                  }
    
                  let Instance = new Axios({
                    timeout: 8000,
                    baseURL: "xxxxxxx"
                  });
                  //暴露实例化这个Axios类里面的方法
                  export default Instance;
    
  • api

          import HttpUtils from "./https";
    
          class Https {
            //新闻请求
            newsLists = (parmas: any) => {
              return HttpUtils.send({
                url: `/news?page=${parmas.page}&pagesize=${parmas.limit}`,
                method: "get"
              });
            };
          }
    
          export default new Https();
    

方式二

  • https

              import axios from 'axios'
    
              //创建自定义实例默认值
              const instance = axios.create({
                baseURL: '/api',
                withCredentials: true // 跨域类型时是否在请求中协带cookie
              })
    
              //创建get/post请求方法
              export default class HttpUtil {
                //定义方法get
                static get(url: string, params = {}) {
                  //返回Promise(异步)
                  return new Promise((resolve, reject) => {
                    //创建请求get,可以(携带url/params)
                    instance
                      .get(url, { params })
                      .then(({ data }) => {
                        resolve(data)
                      })
                      .catch(err => {
                        reject({ err: JSON.stringify(err) })
                      })
                  })
                }
                //定义方法post
                static post(url: string, params = {}) {
                  return new Promise((resolve, reject) => {
                    instance
                      .post(url, { ...params })
                      .then(({ data }) => {
                        resolve(data)
                      })
                      .catch(err => {
                        reject({ err: JSON.stringify(err) })
                      })
                  })
                }
                //定义方法put
                static put(url: string, params = {}) {
                  return new Promise((resolve, reject) => {
                    instance
                      .put(url, { ...params })
                      .then(({ data }) => {
                        resolve(data)
                      })
                      .catch(err => {
                        reject({ err: JSON.stringify(err) })
                      })
                  })
                }
                //定义方法delete
                static delete(url: string, params = {}) {
                  return new Promise((resolve, reject) => {
                    instance
                      .delete(url, { ...params })
                      .then(({ data }) => {
                        resolve(data)
                      })
                      .catch(err => {
                        reject({ err: JSON.stringify(err) })
                      })
                  })
                }
              }
    
  • api

                      import HttpUtils from './http'
                      
                      class Https {
                        newsLists = (parmas: any) => HttpUtils.get(`/news?_page=${parmas}&_limit=8`)
                      }
    
                      export default new Https()