utils -> ajax.js
import { apiUrl, APPKEY } from './config.js';
import util from './util.js';
const app = getApp()
// 不需要特殊处理非200的情况
const ajax = function ({url,data,method='post'}) {
let datas = setSign(JSON.parse(JSON.stringify(data || {})));
let promise = new Promise(function(resolve,reject){
wx.request({
url: apiUrl + url,
data: datas,
method: method,
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
success: function (res) {
if (res.data.code === 10011 || res.data.code === 10012 || res.data.code === 10013 || res.data.code === 10014 || res.data.code === 10021) {
wx.clearStorage();
wx.removeStorage({key: 'userInfo'})
wx.hideLoading()
wx.hideToast()
wx.showToast({
title: '亲, 你人品好到爆, 十万分之一的机会你都能够遇到。',
icon: 'none'
})
wx.reLaunch({
url: '/pages/guide/index',
})
return;
} else if (res.data.code === 10022){
wx.removeStorage({key: 'userInfo'})
wx.showToast({
title: '登录过期或其他设备登录,请重新登录。',
icon: 'none'
})
wx.reLaunch({
url: '/pages/guide/index',
})
return resolve(res.data)
} else if (res.data.code !== 200) {
wx.hideLoading()
wx.hideToast()
wx.showToast({
title: res.data.message,
icon: 'none'
})
reject(res.data)
return;
}
resolve(res.data)
},
fail: function (res) {
wx.showToast({
title: '网络请求失败,请检查您的网络配置',
icon: 'none'
})
}
});
})
return promise;
};
// 需要特殊处理非200的
const fetch = function ({url,data,method='post'}) {
let datas = setSign(JSON.parse(JSON.stringify(data || {})));
let promise = new Promise(function(resolve,reject){
wx.request({
url: apiUrl + url,
data: datas,
method: method,
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
success: function (res) {
if (res.data.code === 10011 || res.data.code === 10012 || res.data.code === 10013 || res.data.code === 10014 || res.data.code === 10021) {
wx.clearStorage();
wx.removeStorage({key: 'userInfo'})
wx.hideLoading()
wx.hideToast()
wx.showToast({
title: '亲, 你人品好到爆, 十万分之一的机会你都能够遇到。',
icon: 'none'
})
wx.reLaunch({
url: '/pages/guide/index',
})
return;
} else if (res.data.code === 10022){
wx.removeStorage({key: 'userInfo'})
wx.showToast({
title: '登录过期或其他设备登录,请重新登录。',
icon: 'none'
})
wx.reLaunch({
url: '/pages/guide/index',
})
return;
} else if (res.data.code !== 200) {
wx.hideLoading()
wx.hideToast()
reject(res.data)
return;
}
resolve(res.data)
},
fail: function (res) {
wx.showToast({
title: '网络请求失败,请检查您的网络配置',
icon: 'none'
})
}
});
})
return promise;
};
let setSign = function (data) {
data.app_key = APPKEY;
data.timestamp = new Date().getTime();
data.app_version = app.globalData.app_version;
data.token = (app.globalData.userInfo || wx.getStorageSync('userInfo') || {}).token || ''
data.sign = util.__joinObj(data);
return data;
};
module.exports = {
ajax,
fetch
};
api -> login -> index.js
import { ajax, fetch } from "../../utils/ajax.js";
// 登录接口
export const loginAjax = function(data){
return ajax({ url: '/xxx',data });
}