第一步、api.js代码:
var apiUrl = "";//接口地址
function getMid(callback) {
var token = uni.getStorageSync('token');
if (!token) {
uni.showToast({
title: '请登录',
icon: 'none',
duration: 1500,
success(e) {
setTimeout(function() {
uni.reLaunch({
url: '../login/login'
});
}, 1500)
}
})
return
}
callback(token);
}
var ajax = {
post(path, data, callback, options) {
this._wxReq('POST', path, data, callback, options);
},
get(path, data, callback, options) {
this._wxReq('GET', path, data, callback, options);
},
_wxReq: (method, path, data, callback, options = {}) => {
uni.request({
url: apiUrl + path,
method,
header: options.header || {
'content-type': 'application/x-www-form-urlencoded'
},
data,
success(res) {
if(res.data.code == 999){
uni.clearStorage();
uni.reLaunch({
title: res.data.msg,
icon: 'success',
duration: 1500,
success(e) {
setTimeout(function() {
uni.reLaunch({
url: '/pages/login/login'
});
}, 1500)
}
})
}else if(res.data.code == 998) {
uni.clearStorage();
uni.showToast({
title: res.data.msg,
icon: 'none',
duration: 5000,
mask: true,
success() {
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login'
})
}, 5000)
}
})
}else{
console.log(path, '请求成功', res.data)
callback(null, res)
}
},
fail(err) {
console.log(path, '请求失败', err)
callback(err)
}
})
}
}
module.exports = {
apiUrl,
getMid,
ajax,
}
第二步、页面引入js:import '@/login.js'
第三步、页面调用方法:
tools.ajax.post('接口地址', data, (err, res) => {
console.log(res,'接口数据')
})