uniapp 封装的网络请求

2020-11-11  本文已影响0人  神一样的队友

Vue.prototype.baseUrl =‘’

let baseUrl_ = ''

let api = ''

Vue.prototype.userloginUrl = baseUrl_ + api + ''

//网络请求封装

Vue.prototype.request = fetch

function clear(str) {

str = str.replace(/,/g, ""); //取消字符串中出现的所有逗号

return str;

}

function fetch({

url,

method = 'POST',

data,

isSign = false,

showLoading = true,

isUploadPic = false,

pic = '',

header = {

'accept': 'application/json',

'authorization':'Bearer ' + management.refreshToken

},

}) {

if (showLoading) {

uni.showLoading({

mask: true

});

}

if (method.toLowerCase() == 'post') {

header['content-type'] = 'application/x-www-form-urlencoded'

}

if (isSign) {

let timestamp = Math.round(new Date().getTime() / 1000).toString();

data.timestamp = timestamp

var dataStr = []

for (var key in data) {

let data_ = key + data[key]

dataStr.push(data_)

}

let sign = dataStr.sort();

var signStr = clear('weichuang!@#2020' + sign + 'weichuang!@#2020');

var signMd5 = this.Md5(signStr).toUpperCase().substring(0, 32).toLowerCase();

data.sign = signMd5

console.log(signStr, signMd5, 112);

}

return new Promise((resolve, reject) => {

if (!isUploadPic) {

uni.request({

url, //仅为示例,并非真实接口地址。

header,

data,

method,

success: (res) => {

if (showLoading) {

uni.hideLoading();

}

if (res.data.code == 1) {

resolve(res.data.data)

} else {

if(res.data.msg != '请登录'){

uni.showToast({

title: res.data.msg,

icon: 'none'

})

}

reject(res.data)

// console.log(res.data);

}

},

fail(err) {

reject(err)

if (showLoading) {

uni.hideLoading();

}

}

});

} else {

uni.uploadFile({

url,

filePath: pic,

name: 'file',

success: (res) => {

if (showLoading) {

uni.hideLoading();

}

var data = JSON.parse(res.data);

uni.showToast({

title: data.msg,

icon: 'none'

})

if (data.code == 1) {

resolve(data.data.pic)

} else {}

},

fail(err) {

console.log(err, 888);

reject(err)

if (showLoading) {

uni.hideLoading();

}

}

})

}

})

}

上一篇下一篇

猜你喜欢

热点阅读