网络请求类封装
const baseUrl= 'https://xxx.xx.xx/';
export default function reqeust(params) {
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + params.url,
timeout:5000,
header: {
'Content-Type': 'application/json',
},
method: params.method || 'POST',
data: params.data || {},
success: resolve,
fail: reject
})
})
}
调用方式一:调用的时候可以直接在程序里面调用。也可以中间封装一层。
reqeust({
url: 'yewu/addCustom',
method: 'POST',
data: paramData,
}).then(res => {
//判断接口调用成功逻辑
}
).catch(err => {
//接口失败逻辑
}
)
调用方式二:中间封装请求网络层的方法
//添加客户
function addCustom(paramData) {
return reqeust({
url: 'yewu/addCustom',
method: 'POST',
data: paramData,
})
}
//添加客户2
function addCustom2(paramData) {
return reqeust({
url: 'yewu/addCustom2',
method: 'POST',
data: paramData,
})
}
然后在js页面。需要调用的地方。引入上面的文件。然后调用次方法进行网络调用。引入包的方法省略。
//上传。 then后面接收的resolve catch后面接收的reject
addCustom(params).then(res => {
console.log(res)
if (res.data.code == "200") {
//代表成功
that.goSuccess();
} else {
that.goFail(res.data.message);
}
}).catch(err => {
console.log(err.errMsg)
that.goFail("网络异常");
})
引入包的两种方式,一种是import。一种是require
import {
addCustom
} from '../../utils/net/httpUtils.js'
import 使用 直接使用 addCustom方法调用。
const HttpUtils= require('../../utils/net/httpUtils.js')
require 使用 HttpUtlis.addCustom调用方法。