小程序 接口请求文件集中化处理

我们在页面有需要和后台交互的接口,基本都是前面域名相同,只有后面字段不同或者参数不同。若少量,很快完成,若大量地址或者一些特定的链接,而且要开发,测试,生产来回切换。就比较超级麻烦。  

即上所述,我们可以写活。定义三个变量, DEV (开发环境域名 -开发人员使用)  SIT (测试域名- 测试人员使用) PRO (生产域名 -线上使用)

 1 // 开发 DEV 测试 SIT 生产 PRO
 2 const isDev = 'SIT';
 3 const ifNoOnline = false; // 部分功能是否上线(默认  true  :上线) false
 4 let host = ''
 5 let wwwNoCar = ''; // no车
 6 let wwwCar = ''; // 宝马车险
 7 let IMLink = ''; // 跳转IM
 8 let wwwGWAuth = ''; // 官微(auth)
20 switch (isDev) {
21   case 'SIT':
22     host = 'https://host.cpic.com.cn/thc-app';
23     wwwNoCar = 'https://wwwnocardsit.ecpic.com.cn';
24     wwwCar = 'https://wwwcarmcdsit.cpic.com.cn';
25     IMLink = 'https://webucstar.cpic.com.cn/webstat/xcxthcmobilewebcall/mbinterface.jsp';
26     wwwGWAuth = 'https://open.weixin.qq.com';  
break; 40 case 'PRO': 41 host = 'https://hostpro.cpic.com.cn/thc-app'; 42 wwwNoCar = 'https://wwwnocar.ecpic.com.cn'; 43 wwwCar = 'https://wwwcarecpic.com.cn';
45 IMLink = 'https://imlink.cpic.com.cn/webstat/xcxthcmobilewebcall/mbinterface.jsp'; //生产地址
wwwGWAuth = 'https://open.weixin.qq.com';
break;
}

1  在api,js中 定义常量 isDev ,四个其余局部变量 ,一个switch 开关,根据我们 定量常量来取不同的值。两种情况,测试,生产。也可加个开发,

const config = {
  isDev,
  dianxin,
  wwwGW,
  wwwGWAuth,
  host,
  wwwCar,
  wwwNoCar,
  IMLink,
  ifNoOnline,
  coupon,
  // 接口地址
  // 7.1	小程序登录
  userLogin: `${host}/thcUser/userLogin`,
  // 7.2	用户注册接口
  userRegister: `${host}/thcUser/registUser`
};

2,定义个常量对象,把上述变量放入其中,接口地址,通过变量host, ${host},(es6写法),来回切换。  

module.exports = config

3, 通过exports 暴露出来,给外部适用。

import api from '../../api.js';

let dev = api.isDev == 'PRO' ? 'release' : 'trial';

let wwwCar =  api.wwwCar;

let url = api.userLogin,

4, 即外部js文件,通过import 导入,并引入在api,即通过api 来找寻对应模块。  

这样,我们就可以方便的更改。可以把大把时间用在享受生活上。比较编程只是为了更好的生活。

猜你喜欢

转载自www.cnblogs.com/liliuyu/p/11494528.html