微信小程序封装请求
请求中可以做一些操作
import {
BASE_URL,
STORAGE_USER,
STORAGE_HEADER
} from '../utils/constant.js' // 需要存的公共数据,都放在这个文件,包括环境
const http = ({
url = '',
param,
...other
} = {}) => {
wx.showLoading({
title: '数据请求中'
});
let timeStart = Date.now();
const data = {
// 在这里面我们可以放入公共的参数后面加的是引用时加入的参数
channelNo: 'xcx',
...param,
}
let common_header = {
token: wx.getStorageSync(STORAGE_HEADER)
}
return new Promise((resolve, reject) => {
wx.request({
url: getUrl(url),
data: data || {},
header: {
// "content-type": "application/x-www-form-urlencoded"
'content-type': 'application/json',
...common_header
},
...other,
complete: (res) => {
wx.hideLoading();
if (res.statusCode = 200) {
if (res.data.code == 200) {
resolve(res.data)
} else if (res.data.code == 500) {
Dialog.alert({
message: res.data.msg,
title: '提示',
confirmButtonText: '确定',
}).then(() => {
})
} else if (res.data.code == 999999) {
Dialog.alert({
message: res.data.msg,
title: '提示',
confirmButtonText: '确定',
}).then(() => {
})
} else if (res.data.code == 300) {
wx.reLaunch({
url: '/pages/login/login',
})
setTimeout(() => {
Dialog.alert({
message: res.data.msg + ',请重新登录',
title: '提示',
confirmButtonText: '确定',
}).then(() => {
})
}, 2000)
}
} else if (res.statusCode == 404) {
Dialog.alert({
message: '服务异常,请稍后重试',
title: '提示',
confirmButtonText: '确定',
}).then(() => {
})
} else {
reject(res)
}
}
})
})
}
const uploadFile = function (params = {}) {
let {
complete,
success,
failure,
data = {},
url,
filePath,
name
} = params, noop = function () {};
if (!filePath) return console.log('filePath不能为空')
if (!url) return console.log('url不能为空')
if (!name) return console.log('name不能为空')
if (!complete || typeof complete != 'function') complete = noop
if (!success || typeof success != 'function') success = noop
if (!failure || typeof failure != 'function') failure = noop
const callback = (res) => {
complete(res)
}
const uploadTask = wx.uploadFile({
url: BASE_URL + url,
filePath,
name,
header: wx.getStorageSync(STORAGE_HEADER),
formData: Object.assign({}, data, common_header),
success: success,
failure: failure
})
uploadTask.onProgressUpdate(callback)
}
const getUrl = (url) => {
if (url.indexOf('://') == -1) {
url = BASE_URL + url;
}
return url
}
// get方法
const _get = (url, param = {}) => {
return http({
url,
param
})
}
const _post = (url, param = {}) => {
return http({
url,
param,
method: 'post'
})
}
const _put = (url, param = {}) => {
return http({
url,
param,
method: 'put'
})
}
const _delete = (url, param = {}) => {
return http({
url,
param,
method: 'put'
})
}
module.exports = {
_get,
_post,
_put,
_delete,
uploadFile
}
封装的方法有这些,当做收藏,嗯!!!开始下一个,工具类!!!