用promise封装微信小程序http请求
1.设置公共访问url,即环境地址
在config文件夹新建env.js
module.exports={
//开发环境
dev:{
// baseUrl:"http://xxx.xxx.xx.xx"
},
//测试环境
// test:{
// baseUrl:"test.xxx.xxx.xx.xx"
// },
// //线上url
prod:{
baseUrl: 'https://xxx.com',
}
}
2.封装promise请求
在config文件夹下新建request.js文件夹
// const {baseUrl} = require('./env.js').test //测试环境
// const {baseUrl} = require('./env.js').dev //开发环境
const {baseUrl} = require('./env.js').prod //线上环境
const subDomain = "api/" //子域名
module.exports = {
request: (url,method,data,isSubDomain)=>{
return new Promise((resolve,reject) => {
// 拼接
let _url = `${baseUrl}/${isSubDomain?subDomain:''}${url}`;
//token和customerId看需求是否增加
var token = wx.getStorageSync('token')
var customerId = wx.getStorageSync('customerId')
wx.request({
url: _url,
data: data,
method: method,
header: {
'content-type':'application/json',
'token':token,
'customerId':customerId
},
//成功回调
success(res){
if(res.statusCode === 200){
//返回的数据
resolve(res.data)
}
else{
console.log("接口有问题")
}
},
//失败回调
fail(){
console.log("接口问题")
}
}
)
})
}
}
3.封装api接口
下面举三种典型例子
const {
request
} = require('./request')
module.exports = {
getlist1: (customerId) => {
return request(`xxx/xxx?customerId=${customerId}`, "post", {}, true)
},
getlist2: (data) => {
return request('xxx/xxx', "post", data, true)
},
getlist3: (shopId, branchId) => {
return request(`xxx/xxx/${shopId}/${branchId}`, "post", {}, true)
},
}
4.使用(与上面三种对应)
const http = require('../../config/api.js');
onLoad: function () {
this.getList1()
this.getList2()
this.getList3()
}
getList1 () {
let customerId = wx.getStorageSync('customerId')
http.getMasterShopId(customerId).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
getList2 () {
http.getMasterShopId({
data1:xx,
data2:xxx
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
getList3 () {
var branchId = xxx;
var shopId= xx;
http.getSideBoard(
branchId,
shopId
).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
每个人,每个项目需求封装的http是不一样的,可以根据实际业务需求,进行改写----------