uniapp請求方法封裝支持請求頭帶token驗證

哈爾濱洛弘科技有限公司 2022-01-07 12:02:51 阅读数:928

uniapp 方法 支持 token
var server = '請求地址';
const session_id = '後臺提供';
const code = '後臺提供';
import md5 from 'js-md5';
//請求接口
export const request = (url, data, method) => {

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

let sign = get_sign(data, code, session_id);
var access_token = uni.getStorageSync('access_token');
var header = {

'content-type': 'application/x-www-form-urlencoded',
sign: sign,
accesstoken: access_token
};
uni.request({

url: server + url,
method: method || 'POST',
data: data || {
},
header: header,
success: (res) => {

if (res.data.status !== 0) {
}
resolve(res.data)
},
fail: (err) => {

console.log(err);
uni.showToast({

title: '嚶嚶嚶!!!網絡出錯了哦',
icon: 'none'
})
reject(err)
}
})
})
}
//文件上傳
export const uploadFile = (url, file, data) => {

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

let sign = get_sign(data, code, session_id);
var access_token = uni.getStorageSync('access_token');
var header = {

'Content-Type': 'multipart/form-data',
sign: sign,
accesstoken: access_token
};
uni.uploadFile({

url: server + url,
method: "POST",
filePath: file['value'],
name: file['field'],
success: (res) => {

resolve(JSON.parse(res.data))
},
fail: (err) => {

console.log(err);
uni.showToast({

title: '嚶嚶嚶!!!網絡出錯了哦',
icon: 'none'
})
reject(err)
}
})
})
}
//微信登錄
export const wxLogin = () => {

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

let _this = this;
uni.showLoading({

title: '微信授權中...'
});
uni.getUserProfile({

lang: 'zh_CN',
desc: '用於完善會員信息',
success: (infoRes) => {

var code = uni.getStorageSync('weixin_login');
var share_token = uni.getStorageSync('share_token');
request('info/wechat_login', {

code: code,
iv: infoRes.iv,
encryptedData: infoRes
.encryptedData,
share_token: share_token
}).then(result => {

uni.hideLoading();
if (result.code == 1) uni.setStorageSync('access_token', result.data
.user_token);
resolve(result.code);
})
},
fail: (err) => {

uni.hideLoading();
}
})
})
}
function get_sign(data, code, session_id) {

var str = '';
for (var a in data) {

str += a + '=' + data[a] + '&';
}
str += 'code=' + code;
var sign = md5(str);
return session_id + '&' + sign;
}

md5類庫比特 uniapp的 js-md5

版权声明:本文为[哈爾濱洛弘科技有限公司]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201071202505544.html