util.js文件
const rootUrl = 'https://yan-app.ilulala.cn'
/**
* 传参格式:{url: url,success:success,fail:fail}
*
*/
// get请求方法
function getRequest(req){
wx.showLoading({
title: '加载中',
})
wx.request({
url: rootUrl + req.url,
method: 'GET',
header: {
'content-type': 'application/json',
'Accept': 'application/json'
},
dataType: 'json',
success: function (res) {
wx.hideLoading();
if (res.data.errno == 0) {
return typeof req.success == "function" && req.success(res.data.data);
} else {
wx.showModal({
title: '错误',
content: res.data.errmsg,
showCancel: false
})
return req.success(false);
}
},
fail: function(res){
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
// post请求方法
function postRequest(req) {
wx.showLoading({
title: '加载中',
})
wx.request({
url: rootUrl + req.url,
method: 'POST',
data: req.data,
header: {
'content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
dataType: 'json',
success: function (res) {
wx.hideLoading();
if(res.data.errno==0){
return typeof req.success == "function" && req.success(res.data.data);
}else{
wx.showModal({
title: '错误',
content: res.data.errmsg,
showCancel: false
})
return req.success(false);
}
},
fail: function (res) {
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof req.fail == "function" && req.fail(res.data);
}
})
}
/**
* 传参格式:key,success
*/
// getStorage存储方法
function _getStorage(key,success){
wx.getStorage({
key: key,
success: function (res) {
return typeof success == "function" && success(res.data);
},
fail: function (res) {
return typeof success == "function" && success(false);
},
complete: function (res) { },
})
}
// getStorageSync存储方法
function _getStorageSync(key,success) {
try {
var value = wx.getStorageSync(key);
if (value) {
// Do something with return value
return typeof success == "function" && success(value);
}
} catch (e) {
// Do something when catch error
console.log(e)
return typeof success == "function" && success(false);
}
}
module.exports = {
getRequest: getRequest,
postRequest: postRequest,
_getStorage: _getStorage,
_getStorageSync: _getStorageSync
}
方法调用
//两种方式
//一,require
var fnc= require('../../../util.js');
fnc.getRequest({url: '', success:function(){}})
//一,import
import { getRequest, postRequest, _getStorageSync, _getStorage } from '../../../util.js'
getRequest({url: '', success:function(){}})