xcxFront/utils/request.js
2024-11-05 10:14:41 +08:00

83 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import baseUrl from "../config/config.js";
// 带 Token 请求
const httpTokenRequest = (opts) => {
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showToast({
title: '网络连接不可用!',
icon: 'none'
});
}
return false
});
let token = uni.getStorageSync('token');
if (token == '' || token == undefined || token == null) {
uni.reLaunch({
url: '/pages/login/login'
});
} else {
let httpDefaultOpts = {
url: baseUrl + opts.url,
data: opts.data,
method: opts.method || 'GET',
header: opts.method == 'get' ? {
'X-Access-Token': token,
'X-Requested-With': 'XMLHttpRequest',
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
} : {
'X-Access-Token': token,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=UTF-8'
},
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
if (res.statusCode == 200) {
//默认api接口正常返回0不正常返回1并给出错误提示
if (res.data.code == 0) {
resolve(res)
}else{
resolve(res)
uni.showToast({
icon:'none',
title:res.data.message
})
}
} else {
if (res.statusCode == 401) {
uni.showModal({
title: '提示',
content: '无权访问',
success: function (res) {
if (res.confirm) {
uni.reLaunch({
url: '/pages/login/login'
});
uni.clearStorageSync();
}
}
});
uni.clearStorageSync();
} else {
resolve(res)
}
}
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
}
};
// 导出去
export default httpTokenRequest;