直接上代码吧~
第一步在utils文件夹下新建api.js
第二步定义请求方式以及baseurl
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';
const baseURL = '';
第三步创建真正的请求
async function request(method, url, data, isLoading) {
return new Promise(function(resolve, reject) {
//设置自己的header
let header = {
'content-type': 'application/json',
'community': 'handicap',
'openid': openid
};
let load = isLoading === false ? false : true
if (load) {
wx.showLoading({
title: '加载中',
})
}
wx.request({
url: baseURL + url,
method: method,
data: method === POST ? JSON.stringify(data) : data,
header: header,
success(res) {
wx.hideLoading()
//请求成功
//判断状态码---errCode状态根据后端定义来判断
if (res.data && res.data.code == 200) {
resolve(res.data.data);
} else if (res.data && res.data.code == 422) {//额外处理某一种code状态
wx.showToast({
title: res.data.data,
icon: 'none',
duration: 3000
})
} else {
reject(res);
//其他异常
wx.showToast({
title: '网络异常,请稍后再试!',
icon: 'none',
duration: 2000
})
}
},
fail(err) {
//请求失败
wx.hideLoading()
reject(err)
}
})
})
}
第四步、统一管理接口(如果接口量多可以单独用一个文件来写)
// 示例 data:入参 request:接受三个参数(请求方式、url、入参、是否需要load状态(默认true))
//获取列表
const API = {
getList: (data) => request(POST, `/specialAid/tencentIm/getList`, data, false),
}
module.exports = {
API: API
}
第五步、用法示例
//在js文件顶部引入
const $api = require('../../utils/api.js').API;
//在需要发送请求时
let that = this;
let data = {
offset: that.data.page,
limit: that.data.pageSize
}
$api.getList(data).then(res => {
console.log(res)
})
.catch(rej => {
console.log(rej)
})
至此就全部完成啦!感谢各位看官!