Axios 二次封装

发布于:2025-07-23 ⋅ 阅读:(19) ⋅ 点赞:(0)

第一步

创建api 初始文件  index.js
import axios from "axios"
// import router from "../router/index"
class Request {
  // 自定义变量
  instance;
  constructor(config) {
    // 创建axios 实例,变量接收
    this.instance = axios.create(config);
    // 添加请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // config.headers.token = JSON.parse(localStorage.getItem("giant_userdata")).sessionkey;
        return config;
      },
      (error) => {
        return error;
      }
    );
    // 添加相应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        if(res.status == 200){
          if(res.data.code == '503'){
              this.countDown503()
          }else{
            return res;
          }
        }
      },
      (error) => {
        return error;
      }
    );
  }
  // 2
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then((res) => {
        return resolve(res);
      }).catch((error) => {
        return reject(error);
      });
    });
  }


  // 1
  get(config) {
    return this.request({
      ...config,
      method: "GET",
    });
  }
  post(config) {
    const formData = new FormData()
    for (const key in config.params) {
      formData.append(key, config.params[key])
    }
    return this.request({
      data: formData,
      url: config.url,
      method: "POST",
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  postblob(config) {  
    const formData = new FormData()
    for (const key in config.params) {
      formData.append(key, config.params[key])
    }
    return this.request({
      data: formData,
      url: config.url,
      method: "POST", 
      headers: {
        'Content-Type': 'application/x-msdownload'
      },
      responseType: 'blob'
    })
  }
  // 
  postjson(config) {
    return this.request({
      ...config,
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
  // delete(config) {
  //   return this.request({
  //     ...config,
  //     method: "DELETE",
  //   });
  // }
}

export default Request;

第二部

创建 自定义对应的模块js文件  如: login.js
引入第一步文件js
import { request } from '../config.js'
//  分页
export const flowpages = (params) => {
  return request.post({
    url: '/flow/pages',
    params
  })
}
//修改
export const flowrupdate = (params) => {
  return request.postjson({
    url: '/flow/update',
    data: JSON.stringify(params)
  })
}
//后端返回数据流前端处理导出
export const exportflowcasePages = (params) => {
  return request.postblob( {
    url: '/export/flow/casePages',
    params
  })
}



第三部

引入第二部文件到对应的vue项目
import {
  exportflowcasePages,
  flowcasePages,
  flowpages
} from "@/api/index/index.js"

进行使用

      flowpages(tmpParams)
        .then((res) => {
          if (res.status == 200) {
            if (typeof res.data != "object") {
              res.data = JSON.parse(res.data)
            }
            if (res.data.code == 200) {
      			console.log(res.data,'文件信息')
            } else {
              _this.$toast(
                res.data.msg ? res.data.msg : "网络加载失败,请稍后再试"
              )
            }
          } else {
            _this.$toast(
              res.data.msg ? res.data.msg : "网络加载失败,请稍后再试"
            )
          }
        })
        .catch((err) => {
          _this.$toast("网络加载失败,请稍后再试")
        })

此处后端返回数据流导出设置

 exportflowcasePages(tmpParams)
        .then((res) => {
          if (res.status == 200) {
            const elink = document.createElement('a')
            elink.download = '列表.xls'
            elink.style.display = 'none'
            const blob = new Blob([res.data], { type: 'application/x-msdownload' })
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
          } else {
            _this.$toast(
              res.data.msg ? res.data.msg : "网络加载失败,请稍后再试"
            )
          }
        })
        .catch((err) => {
          _this.$toast("网络加载失败,请稍后再试")
        })

网站公告

今日签到

点亮在社区的每一天
去签到