今日分享:微信小程序封装request请求
废话不多说 直接上代码~
1.utils 下创建utils.js文件
var api = require('../config/api.js');
var app = getApp();
/**
* 封封微信的的request
*/
function request(url, data, method, loading) {
data = data || {};
if (loading) {
wx.showLoading({
title: '加载中',
})
}
return new Promise(function(resolve, reject) {
// api.apiRoot我自己定义的域名地址
wx.request({
url: api.apiRoot + url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'token': wx.getStorageSync('token')
},
success: function(res) {
if (res.statusCode == 200) {
if(res.data.code == 2) {
// 登录过期 重新登录
// app.login()
} else if (res.data.code == 3) {
// 清除登录相关内容
try {
wx.removeStorageSync('userId');
wx.removeStorageSync('token');
wx.removeStorageSync('phone');
} catch (e) {
// Do something when catch error
}
// 切换到登录页面
wx.navigateTo({
url: '/page/auth/login/login'
});
reject(res.data.msg);
} else {
resolve(res.data);
}
} else {
reject(res.data.msg);
}
},
fail: function(err) {
reject(err)
wx.showToast({
title: "网络错误,请重新链接",
duration: 1000
});
},
complete: function () {
if(loading) {
wx.hideLoading();
}
}
})
});
}
module.exports = {
request
}
2. api下创建各模块js文件 写接口地址 建议大家 模块化哈 代码如下:(user.js)
import util from '../utils/util'
//获取用户
function getContractInfo(params) {
return util.request('xx/xx/info', params, 'GET');
}
// 这个是post请求 并添加loading
function ceshi(data) {
return util.request('xx/xx/xx', data, 'POST', true);
}
module.exports = {
getContractInfo: getContractInfo,
ceshi: ceshi
}
3.页面js引用 只粘了部分给大家参考~
var ceshiServer = require('../../../api/user')
getOrderList() {
const that = this
const params = {
isCustomer: false,
current: 1,
size: 10
}
// 调用的上面xx/xx/info 这个接口
ceshiServer.getContractInfo(params).then(res => {
//接口返回 一系列处理
})
},
以上 结束 可能看起来 比较复杂 但我个人比较喜欢这么用 大家可以按照自己的代码风格封装 非常easy~