/**
* @Token 后台约定的键值名
* @loginPage 登录页路径(用户登录过期时跳转)
* @baseUrl 接口域名前缀
* @fileUrl 文件上传路径
*/
const Token = '后台约定的token名';
const loginPage = "/pages/user/login/login";
const baseUrl = "你的接口地址";
const fileUrl = baseUrl + "storage/upload";
const app = getApp();
/**
* @description GET请求
* @param {String} url 请求的地址
* @param {Object} data 请求参数
* @param {Boolean} loadingType 是否显示加载中浮动框 默认false
*/
const get = (url, data, loadingType = false) => {
return new Promise((resolve, reject) => {
request('GET', url, data, loadingType).then(res => {
resolve(res);
}).catch(err => {
reject(err);
})
})
}
/**
* @description POST请求
* @param {String} url 请求的地址
* @param {Object} data 请求参数
* @param {Boolean} loadingType 是否显示加载中浮动框 默认false
*/
const post = (url, data, loadingType = false) => {
return new Promise((resolve, reject) => {
request('POST', url, data, loadingType).then(res => {
resolve(res);
}).catch(err => {
reject(err);
})
})
}
/**
* @description 小程序文件上传
* @param {Object} event 调用微信上传后返回的event数据
* @param {Object} formData wx.uploadFile请求中的formData
* @param {Boolean} loadingType 是否显示加载中浮动框 默认false
*/
const uploadFile = (event, formData, loadingType = false) => {
return new Promise((resolve, reject) => {
loadingType && showLoading();
const file = event.detail.file;
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
wx.uploadFile({
url: fileUrl,
filePath: file.url,
name: 'file',
formData,
success(res) {
if (res.statusCode === 200) {
loadingType && hideLoading();
resolve(res);
} else {
reject(res);
}
},
fail(err) {
loadingType && hideLoading();
reject(err);
}
});
})
}
/**
* @description 网络请求
* @param {String} method 请求方法post/get
* @param {String} url 请求地址
* @param {Boolean} loadingType 是否显示加载中浮动框
*/
const request = (method, url, data, loadingType) => {
return new Promise((resolve, reject) => {
loadingType && showLoading();
wx.request({
url: baseUrl + url,
dataType: 'json',
method,
header: {
"content-type": "application/json", //修改此处即可
[Token]: wx.getStorageSync('token')
},
data,
success: (res) => {
loadingType && hideLoading();
if (res.statusCode === 200) {
if (res.data.errno === 0) {
resolve(res.data);
} else if (res.data.errno === 501) {
try {
wx.removeStorageSync('userInfo');
wx.removeStorageSync('token');
} catch (e) {
console.log('Storage删除错误', e);
}
wx.navigateTo({
url: loginPage
});
} else {
reject(res);
}
} else {
reject(res);
}
},
fail: function (err) {
loadingType && hideLoading();
reject(err)
},
})
})
}
/**
* @showLoading 显示加载中
* @hideLoading 隐藏加载中
* @loadingCount 防止多接口请求时showLoading异常
*/
const showLoading = () => {
app.globalData.loadingCount++;
wx.showLoading({
title: '加载中',
})
}
const hideLoading = () => {
app.globalData.loadingCount--;
if (app.globalData.loadingCount === 0) {
wx.hideLoading()
}
}
module.exports = {
get,
post,
uploadFile
}
微信小程序request.js封装
最新推荐文章于 2024-03-31 21:53:00 发布