在项目的开发中有三个环境
开发环境
测试环境
生产环境
访问接口数据时,例如:商品接口会是【域名】/api/xxx/xxx
当环境不同时,直接修改域名即可。这是为什么要封装请求。
一、封装的意义
代码更简单,维护更方便
var api= 'http://10.1.8.22:1001';//域名
apiList: {
usersLogin: api+ '/storeroom/usersLogin/usersLogin', //登录
queryCustomersList: api+ '/storeroom/repertory/queryCustomersList', //查询客户
insertCustomersBatch: api+ '/storeroom/repertory/insertCustomersBatch', //查询客户
},
二、使用步骤
1.post请求
代码如下(示例):
apiPost: function (api, data, callback) {
var that = this;
//请求头
var header = {
// 'content-type': 'application/x-www-form-urlencoded'
};
//请求
wx.request({
url: api,
data: data,
method: 'POST',
dataType: 'json',
header: header,
success: (res) => {
// console.log("res:", res);
return callback(res.data);//成功后回调
},
fail: function (res) {
wx.showModal({
// cancelColor: 'cancelColor',
title: '调用出错啦',
content: res
})
},
complete: function (res) {
console.log("res:", res);
}
})
},
调用
app.apiPost(app.apiList.usersLogin+that.data.username+'/'+that.data.password,{},res=>{
console.log(res)
})
2.get请求
代码如下(示例):
apiGet: function (api, data, callback) {
var header = {
'content-type': 'application/json;charset=UTF-8',
"X-Requested-With": 'XMLHttpRequest',
};
wx.request({
url: api,
data: data,
method: 'GET',
dataType: 'json',
header: header,
success: function (res) {
callback(res.data)
},
fail: function (res) {
console.error(api+ '请求失败')
},
complete: function (res) {
}
})
},
调用
app.apiGet(app.apiList.queryCustomersList,data,res=>{//data就是拼接在api路径后所需的参数
console.log(res)
})