公司开发完微信小程序,又让开发支付宝小程序,稳住,虽然自己做iOS,但是会开发小程序也不错哦。上吧皮卡丘。
直接贴代码 request.js
/开发
// const baseUrl = 'http://192.168.45.191:9183';
//测试
const baseUrl = 'http://192.168.100.142:9183';
//token
var tokenKey = "token";
// 登录地址, 根据这个地址来设置token
var loginUrl = "/dayan/scf/user/user/login";
// 例外不用token的地址
var exceptionAddrArr = [
'',//暂时是个例子
];
//剪头函数表达式得写法 (参数1, 参数2, …, 参数N) => { 函数声明 }
function http(url, method, param, success, fail) {
my.showLoading({
title: '正在加载...'
});
// 记录发起请求的当前时间
let timeStart = Date.now();
//设置header
CreateHeader(url, function (header) {
//发起请求
my.request({
url: baseUrl + url,
data: param,
headers: header,
method: method,
//检测是否传参completeData,如果有则执行回调completeData(res)
complete(res) {
console.log(`耗时${Date.now() - timeStart}`, baseUrl + url);
if (res.status === 200) {
//登录接口成功后设置token
if (url === loginUrl) {
//同步存储token和登录信息
my.setStorageSync({
key: tokenKey, // 缓存数据的key
data: res.headers.token // 要缓存的数据
});
my.setStorageSync({
key: 'loginInfo', // 缓存数据的key
data: res.data.data // 要缓存的数据
});
}
if (res.data.code === '000000') {//正常返回数据
my.stopPullDownRefresh()
success(res.data)
//为了兼容部分andriod 异步请求是隐藏不掉弹框加得延时
setTimeout(function () {
my.hideLoading();
}, 1000);
} else if (res.data.code === '900001') {//登录超时,请重新登录
my.showToast({
type: 'none',
content: res.data.message,
duration: 3000,
success: () => {
my.navigateTo({
url: '/pages/login/login',
})
},
});
}else{//其他服务端状态码
my.showToast({
type: 'exception',
content: res.data.message,
duration: 3000,
})
//为了兼容部分andriod 异步请求是隐藏不掉弹框加得延时
setTimeout(function () {
my.hideLoading();
}, 1000);
fail(res)
my.stopPullDownRefresh()
}
}else{
setTimeout(function () {
my.hideLoading();
}, 1000);
fail(res)
my.stopPullDownRefresh()
}
}
})
});
}
/**
* @param url:String 请求地址(根据请求地址判断是否添加token)
* @param complete:Function 回调函数
*/
function CreateHeader(url, complete) {
var header = {
'content-type': 'application/json'
}
if (exceptionAddrArr.indexOf(url) === -1) { //排除请求的地址不需要token的地址
my.getStorage({
key: tokenKey,
success: function (res) {
header.token = res.data;
},
fail: function (error) {
console.log(error);
},
complete: function () {
complete && typeof complete === 'function' ? complete(header) : null;
}
});
} else {
complete && typeof complete === 'function' ? complete(header) : null;
}
}
module.exports = {
http: http
}
使用
const api = require('../../request.js')
api.http('url','get',{},success => {
this.setData({
sectionVoList: success.data.sectionVoList
});
},fail=>{
});