im-ui-mobile
Version:
A Vue3.0 + Typescript instant messaging component library for Uniapp
85 lines (78 loc) • 2.82 kB
JavaScript
export default class Requester {
constructor(baseURL, options = {}) {
this.baseURL = baseURL;
this.options = options;
this.timeout = options.timeout || 10000;
this.header = {
'Content-Type': 'application/json',
...options.header
};
}
// 设置 token
setToken(token) {
this.header['Authorization'] = `Bearer ${token}`;
this.header['AccessToken'] = token;
}
// 基础请求方法
async request(options) {
this.options = {
...this.options,
...options
}
this.header = {
...this.header,
...options.header
}
this.options.url = this.baseURL + this.options.url
this.options.header = this.header
this.options.timeout = this.timeout
return new Promise((resolve, reject) => {
uni.request({
...this.options,
success: (res) => {
const data = res.data;
data.result = data.result || data.data;
if (data.code >= 200 && data.code < 300) {
resolve(data);
} else if (data.code === 401) {
// 清除用户信息,提示登录
uni.showToast({
icon: 'none',
title: '请先登录',
});
setTimeout(() => {
clearToken();
uni.removeStorageSync('expired');
uni.removeStorageSync("user");
uni.setStorageSync('keepLoggedIn', false);
reject(res);
}, 1000);
} else {
uni.showToast({
icon: 'none',
title: data.message || '请求错误',
});
console.error('请求错误', res);
reject(res);
}
},
fail: (err) => {
reject(err);
}
});
});
}
// 快捷方法
get(url, data, options) {
return this.request({ url, method: 'GET', data, ...options });
}
post(url, data, options) {
return this.request({ url, method: 'POST', data, ...options });
}
put(url, data, options) {
return this.request({ url, method: 'PUT', data, ...options });
}
delete(url, data, options) {
return this.request({ url, method: 'DELETE', data, ...options });
}
}