浙里办通用请求的封装

开发浙里办应用都知道,我们发布到线上的接口需要按这样的方式去请求:

但是往往本地开发的时候是连得公司测试环境,而且接口调用方式也不长这样。我第一次开发浙里办项目的时候并没有注意到这个问题,本地调完了,才看到线上的请求方式不一样,当时着急上线,就来回修改,浪费了很多时间。。。

后来我整理下,如果本地联调的时候接口传参和线上传参一样,发布线上只需切换下判断参数,那不是就不用来回调整了。于是现在的请求是这样的:

request.js

import Vue from 'vue';
import axios from "axios";
import router from "../router/index";
import errorMsg from "./error"; // 错误提示
import envUrls from '@/core/envChange' // 定义一些基础变量的文件
import urls from '@/core/interfaceUrls' // 本地接口和浙里办注册接口的对应关系
import { mgop } from "@aligov/jssdk-mgop"; // 加载浙里办 mgop依赖
import { Toast, Notify } from 'vant';
Vue.use(Toast, Notify);

let httpServer = null

// create an axios instance
const service = axios.create({
  baseURL: envUrls.BASE_URL,
  timeout: 50000,
  headers: {
    "Content-Type": "application/json"
  }
});

// request interceptor
service.interceptors.request.use(
  config => {
    // 获取设置接口token  根据自己场景添加
    const token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    config.headers["X-Gisq-Token"] = `Bearer ${token}`;
    return config;
  },
  error => {
    // do something with request error
    console.log(error);
    return Promise.reject(error);
  }
);
// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code && res.code !== 200 || response.status !== 200) {
      Notify({
        type: 'danger',
        duration: 5 * 1000,
        message: res.message || "Error"
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    if (error && error.response) {
      const msg = errorMsg(error.response);
      Notify({
        type: 'danger',
        duration: 5 * 1000,
        message: msg
      });
      if (error.response.status === 401) {
        router.replace("/Login");
        sessionStorage.clear();
      }
    }
    if (error && error.message === "Network Error") {
      router.replace("/Login");
      sessionStorage.clear();
    }
    return Promise.reject(error);
  }
);

// 接口报错处理
const checkMgopFail = function (err) {
  if (err.code === 1) {
    Toast(err.message)
  } else if (err.errorMessage) {
    Toast(err.errorMessage)
  } else if (err.data && !Object.keys(err.data).length) {
    console.log('报错接口--------', err.api);
    err.ret.length && Toast(err.ret[0]) || Toast('请求失败,请稍后重试')
  }
}

// 获取浙里办接口地址处理
const setUrl = function (url) {
  if (url.indexOf('?') !== -1) {
    return url.split('?')[0]
  } else {
    return url
  }
}
// 处理拼接参数
const _paramify = function (obj) {
  var str = "";
  for (var key in obj) {
    if (str !== "") {
      str += "&";
    }
    str += key + "=" + obj[key];
  }
  return str;
};

// 本地联调时 
// noload 不要loading效果 为true 即不需要loading, false或者不存在(默认) 需要loading
class baseServer {
  mgopGET(url, params, options, noload) {
    params = params || {};
    params.ts = new Date().getTime();
    options = options || {};
    options.method = "GET";
    options.url = url;
    options.params = params;
    let toast = null
    if (!noload) {
      toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }
    return service.request(options).then(res => {
      if (res) {
        !noload && toast.clear() || ''
        return res
      }
    }).catch(err => {
      !noload && toast.clear() || ''
      console.log('err', err);
    })
  }
  mgopPOST(url, data, options, noload, isQuery) {
    // isQuery 是否是query方式传参
    // 如果不是Data包裹的 即通过地址栏传值
    if (isQuery) {
      const getParams = _paramify(data);
      url += `?${getParams}`;
    }
    options = options || {};
    options.method = "POST";
    options.url = url;
    options.data = data;
    let toast = null
    if (!noload) {
      toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }
    return service.request(options).then(res => {
      if (res) {
        !noload && toast.clear() || ''
        return res
      }
    }).catch(err => {
      !noload && toast.clear() || ''
      console.log('err', err);
    })
  }
}
// 线上联调时(浙里办环境 需要 mgop 方式调用)
class mgopServer {
  mgopGET = (url, data = {}, extra = {}, noload) => {
    let toast = null
    if (!noload) {
      toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }
    const promise = new Promise((resolve, reject) => {
      const params = {
        api: urls[setUrl(url)],
        host: "https://mapi.zjzwfw.gov.cn/",
        dataType: "JSON",
        type: "GET",
        appKey: envUrls.APPKEY,
        data: data,
        ...extra
      };
      if (extra.headers) params.header = extra.headers;
      else {
        const token = sessionStorage.getItem("access_token")
        params.header = {
          Authorization: token ? `bearer ${token}` : '',
          "token": token ? `Bearer ${token}` : '',
          "X-Gisq-Token-QYDM": "33"
        }
      }
      mgop({
        ...params,
        onSuccess: res => {
          console.log('------GET响应------', res);
          !noload && toast.clear() || ''
          if (res.data) {
            resolve(res.data);
          } else {
            reject();
          }
        },
        onFail: err => {
          !noload && toast.clear() || ''
          console.log(err, '错误返回');
          checkMgopFail(err)
          reject();
        }
      });
    });
    return promise;
  };
  mgopPOST(url, data = {}, extra = {}, noload) {
    let toast = null
    if (!noload) {
      toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }
    const promise = new Promise((resolve, reject) => {
      const params = {
        api: urls[setUrl(url)],
        host: "https://mapi.zjzwfw.gov.cn/",
        dataType: "JSON",
        type: "POST",
        appKey: envUrls.APPKEY,
        data: data,
        ...extra
      };
      if (extra.headers) {
        params.header = extra.headers;
      }
      else {
        const token = sessionStorage.getItem("access_token")
        params.header = {
          Authorization: token ? `bearer ${token}` : '',
          "token": token ? `Bearer ${token}` : '',
          "X-Gisq-Token-QYDM": "33"
        }
      }
      mgop({
        ...params,
        onSuccess: res => {
          console.log('------POST响应------', res);
          !noload && toast.clear() || ''
          if (res.data) {
            resolve(res.data);
          } else {
            reject();
          }
        },
        onFail: err => {
          !noload && toast.clear() || ''
          console.log(err, '错误返回');
          checkMgopFail(err)
          reject();
        }
      });
    });
    return promise;
  }
}
// 判断是否是浙里办环境 走不同类型的接口                                                                                                                                                                                                                                                                                                                                                
if (!envUrls.IS_ZLB) {
  httpServer = new baseServer()
} else {
  httpServer = new mgopServer()
}

export default httpServer;

main.js:

import http from '@/service/request'
Vue.prototype.$http = http

interfaceUrls.js:

const urls = {
  '本地接口地址': '浙里办对应接口地址'
}
export default urls

此文件放的接口的对应关系。“本地接口地址”即除了baseURL外后面的地址(不包含传参部分),“浙里办对应接口地址”对应如图“API名称”处的地址:

使用:

配置文件里的 IS_ZLB: true,如果本地联调,置为 false 即可,如果接口都在RIS已注册好了,也可以本地切换到线上地址进行联调,置为 true 即可。

const params = {}
this.$http.mgopPOST('/xxx/xxx/xxxx/xxxx', params).then().catch()
posted @ 2023-03-05 18:31  拾忆-iiii  阅读(472)  评论(0编辑  收藏  举报