微信小程序统一管理接口

小程序上线后要增加功能,不能用线上的接口联调,怎么办?

1.微信开发者工具,详情,勾上该选项

2.修改apiHost为本地接口地址

3.api.js

var app = getApp();
var api = {
    cityApi:app.apiHost+'/applet/index.php?route=city/list',
...
}
module.exports=api;

一个模块要想要对外暴露其内部的私有变量和函数,只能通过module.export

把接口的地址全部放在api.js中就可以模块化的管理接口了

4.app.js中用wx.request把接口请求封装起来

fetch(url, data, method, callback) {
if (method=="GET"){
var header= {'Content-Type': 'application/json'}
}
else if (method == "POST") {
var header = { "Content-Type": "application/x-www-form-urlencoded" }
}
wx.request({
url,
data: data,
method: method,
header: header,
success(res) {
callback(null, res.data);
},
fail(e) {
callback(e);
}
})
},

5.使用接口

  app.fetch(API.cityApi, {}, 'POST', (success, data) => {
              if (data.code == 0) {

 

posted @ 2018-06-20 11:33  刘倩蓉  阅读(2049)  评论(0编辑  收藏  举报