vue项目接口请求的方法封装

706 阅读1分钟

在vue项目开发中会调用各种各样的后端接口,需要封装成单独的文件便于每个接口的管理,于是有了如下的方法:

1.请求方法的封装

let AxiosRequest = function (url, method, bodyType) {
  this.url = url;                //请求地址
  this.method = method;          //请求类型get/post
  this.bodyType = bodyType;      //请求参数类型
  var _self = this;
  return function (query, callback) {
    var method = _self.method;
    var url = _self.url;
    var cTypeHeader = {          //请求头部
      'Content-Type': bodyType || "application/x-www-form-urlencoded; charset=utf-8",
    }

    if (query._path) {
      url += "/" + query._path;
      delete query._path;
      let t = qs.stringify(query);
      url += "?" + t;
    } else {}

    if (method !== "get" && cTypeHeader['Content-Type'].search("application/x-www-form-urlencoded") !== -1) {
      query = qs.stringify(query);
    }

    var options = {
      headers: cTypeHeader,
    }

    var token = localStorage.getItem("token");
    if(token) {
      options.headers.Authorization = token;
    }

    if(method === "get") {
      axios.get(url, {
        params: query,
        headers: options.headers,
      }).then((data) =>{
        if(data && data.data && data.data.status === 401) {
          if(localStorage.getItem('token')){
            localStorage.clear();
            MessageBox.confirm('登录失效,请重新登录!', '提示', {
              confirmButtonText: '确定',
              showCancelButton:false,
              type: 'warning',
              center: true,
            }).then(() => {
              mainFile.$router.push({
              name: 'LoginReg'
            })

            }).catch(() => {

            });

          }else{
            localStorage.clear();
          }


        }
        else {
          if (typeof (callback) === "function") {
            callback(data);
          }
        }

      });
    }
    else {
      axios[method](url, query, options).then(function (data) {
        if(data && data.data && data.data.status === 401) {
          if(localStorage.getItem('token')){
            localStorage.clear();
            MessageBox.confirm('登录失效,请重新登录!', '提示', {
              confirmButtonText: '确定',
              showCancelButton:false,
              type: 'warning',
              center: true,
            }).then(() => {
              mainFile.$router.push({
                name: 'LoginReg'
              })

            }).catch(() => {

            });

          }else{
            localStorage.clear();
          }
        }
        else {
          if (typeof (callback) === "function") {
            callback(data);
          }
        }
      });
    }

  }
}

const adapter = {}
for (let k in config) {
  var item = config[k];
  if (item.url && item.method) {
    adapter[k] = new AxiosRequest(item.url, item.method, item.bodyType);
  }
}
adapter.config = config;


export default adapter

2.请求方法文件 config.js

const api = 'http://ceshi.com/cc';
const config = {
  ceshiList: {
    url: `${api}/ceshi/ceshi1List`,
    method: "post",
    bodyType: "application/x-www-form-urlencoded",
    tips: "测试1列表"
  },
  ceshi2List: {
    url: `${api}/ceshi/ceshi2List`,
    method: "get",
    bodyType: "application/json",
    tips: "测试2列表"
  },
}