56 lines
1.3 KiB
JavaScript
56 lines
1.3 KiB
JavaScript
import { BASE_URL } from "../../constant/base";
|
|
|
|
const defaultConfig = {
|
|
header: {
|
|
Authorization: '', // 可在此动态设置 token
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
},
|
|
};
|
|
|
|
function request(url, args = {}, method = 'POST', customConfig = {}) {
|
|
// 判断 url 是否以 http 开头
|
|
if (!/^http/.test(url)) {
|
|
url = BASE_URL + url;
|
|
}
|
|
// 动态获取 token
|
|
const token = uni.getStorageSync('token');
|
|
let header = {
|
|
...defaultConfig.header,
|
|
...customConfig.header
|
|
};
|
|
// 判断是否需要 token
|
|
if (customConfig.noToken) {
|
|
delete header.Authorization;
|
|
} else if (token) {
|
|
header.Authorization = `Basic ${token}`;
|
|
} else {
|
|
delete header.Authorization;
|
|
}
|
|
const config = {
|
|
...defaultConfig,
|
|
...customConfig,
|
|
header
|
|
};
|
|
return new Promise((resolve, reject) => {
|
|
uni.request({
|
|
url,
|
|
data: args,
|
|
method,
|
|
...config,
|
|
success: (res) => resolve(res.data),
|
|
fail: (err) => reject(err)
|
|
});
|
|
});
|
|
}
|
|
|
|
// 默认 POST
|
|
request.post = function(url, args = {}) {
|
|
return request(url, args, 'POST');
|
|
};
|
|
|
|
// 支持 GET
|
|
request.get = function(url, args = {}) {
|
|
return request(url, args, 'GET');
|
|
};
|
|
|
|
export default request; |