yitisheng-mini-app/common/request.js

125 lines
3.7 KiB
JavaScript

/*网络请求*/
import operate from '@/common/operate'
// vuex 的使用 详情参考官网 https://uniapp.dcloud.io/vue-vuex
import store from '../store/index.js'
let token= uni.getStorageSync('token')
token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDU4ODQ5MDYsInVzZXJuYW1lIjoid2FuZ3hpYW9taW5nIn0.jRSoihlbs08ONDIsrk2U3l3pw8ZQK2Z1Oc2-mQaf7pw'
export default class Request {
http(param) {
// 请求参数
var url = param.url,
method = param.method,
header = {
'X-Access-Token':param.token || "",
},
data = param.data || {},
hideLoading = param.hideLoading || false;
/*token = param.token || "",*/
//拼接完整请求地址
var requestUrl = operate.api + url;
console.log(requestUrl)
//拼接完整请求地址(根据环境切换)
// var requestUrl = operate.api() + url;
//请求方式:GET或POST(POST需配置
// header: {'content-type' : "application/x-www-form-urlencoded"},)
if (method) {
method = method.toUpperCase(); //小写改为大写
if (method === "POST") {
header = {"content-type":'application/json',...header}
} else {
header = {"content-type":'application/x-www-form-urlencoded',...header}
}
}
//加载圈
if (!hideLoading) {
uni.showLoading({
title: '加载中...'
});
}
// 返回promise
return new Promise((resolve, reject) => {
// 请求
uni.request({
url: requestUrl,
data: data,
method: method,
header: header,
success: (res) => {
console.log('执行http请求')
// 判断 请求api 格式是否正确
/*if (res.statusCode && res.statusCode != 200) {
uni.showToast({
title: "api错误" + res.errMsg,
icon: 'none'
});
return;
}*/
// 将结果抛出
resolve(res.data)
},
//请求失败
fail: (e) => {
uni.showToast({
title: "" + e.data.msg,
icon: 'none'
});
resolve(e.data);
},
//请求完成
complete() {
//隐藏加载
if (!hideLoading) {
uni.hideLoading();
}
resolve();
return;
}
})
})
}
get(url,data,options={}){
options.method='get';
options.data=data;
options.url=url;
options.token=token;
return this.http(options);
}
get(url,data,headers={},options={}){
options.method='get';
options.data=data;
options.url=url;
options.token=token;
return this.http(options);
}
post(url,data,options={}){
options.method='post';
options.data=data;
options.url=url;
options.token=token;
return this.http(options);
}
post(url,data,headers={},options={}){
options.method='post';
options.data=data;
options.url=url;
options.token=token;
return this.http(options);
}
delete(url,data,options={}){
options.method='delete';
options.data=data;
options.url=url;
options.token=token;
return this.http(options);
}
}