request.js
const debug = false
const basePath='192.168.1.100/' //调试接口地址
const API = {
user:(userId) => basePath + "index/user/" + userId, //用户信息
}
// 加载动画
function loadingAnimate() {
wx.showLoading({
title: "加载中",
mask: true
});
}
// 请求接口
function request(options = {}) {
// 根据showLoading参数决定是否显示加载效果
let showLoading = options.showLoading ? options.showLoading : false
if (showLoading) loadingAnimate()
// 默认头部
if (options.header === undefined) {
options.header = {
'content-type': 'application/json'
}
}
// 如果token有值则带上
let token = wx.getStorageSync("desKey");
if (token) {
options.header = Object.assign({}, options.header, {
'Authorization': token
});
}
options.method = options.method ? options.method : 'GET'
return new Promise((resolve, reject) => {
options.success = res => {
debug && sendErrLog(options, 'success')
if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
//服务端业务处理正常结束
resolve(res)
} else {
reqStatus(res.data.errCode)
reject(res)
}
}
options.fail = err => {
sendErrLog(err, 'fail')
reject(err)
}
options.complete = res => {
wx.hideLoading()
}
wx.request(options)
})
}
// 日志输出
function sendErrLog(req, status) {
let title = '调用微信请求接口成功!'
if (status == 'fail') {
title = '请求接口错误!'
}
console.group(title)
console.info("[请求Url]", req.url)
console.info("[请求Header]", req.header)
console.info("[请求Data]", req.data)
if (status == 'fail') console.info("[请求Result]", req)
console.groupEnd();
}
// 接口状态判断
function reqStatus(statusCode) {
switch (statusCode) {
case 401:
wx.showModal({
content: "您的账号已在别处登录,请刷新页面重新登录",
showCancel: false,
success: data => {
wx.redirectTo({
url: "../login/login"
})
}
});
break;
case 503:
wx.showModal({
content: "服务繁忙,请稍后再试!",
showCancel: false
});
break;
default:
break;
}
}
module.exports={
API,
request
}
// 使用
index.js
const req = require('../util/request')
const userId = wx.getStorageSync("userId")
req.request({
url: req.API.user(userId)
}).then(res=>{
//code
})