request.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import config from "@/config";
  2. import store from "../store";
  3. const logout = () => {
  4. uni.removeStorageSync('token');
  5. uni.removeStorageSync('chatToken');
  6. uni.removeStorageSync('vuex_state');
  7. store.dispatch('app/changeOrganization', {});
  8. store.dispatch('app/changeProject', {});
  9. store.dispatch('app/changeUser', {});
  10. store.dispatch('app/changeIdentity', {});
  11. uni.removeTabBarBadge({
  12. index: 1
  13. })
  14. uni.navigateTo({
  15. url: '/pages/login/login'
  16. })
  17. }
  18. export function request(options) {
  19. return new Promise((resolve, reject) => {
  20. let header = options.header || {
  21. 'Content-Type': 'application/json'
  22. }
  23. if (uni.getStorageSync('token')) header['token'] = uni.getStorageSync('token');
  24. if (options.url === '/im/message/save') header['token'] = uni.getStorageSync('systemChatToken');
  25. uni.request({
  26. url: config.baseUrl + options.url, // 服务器url
  27. method: options.method || 'GET', // 请求方法,默认为GET
  28. data: options.data || {}, // 请求参数
  29. header: header, // 设置请求的 header
  30. success: (res) => {
  31. // 请求成功
  32. if (res.statusCode === 200) {
  33. resolve(res.data);
  34. if (res.data.code != 200) {
  35. if (res.data.code == 20005) {
  36. if (!uni.getStorageSync('token')) return;
  37. uni.showToast({
  38. title: '登录过期,请重新登录',
  39. icon: 'none'
  40. })
  41. logout();
  42. return;
  43. }
  44. uni.showToast({
  45. title: res.data.message,
  46. icon: 'none'
  47. })
  48. }
  49. } else {
  50. // 可以根据项目要求修改错误处理
  51. reject(res.data);
  52. uni.hideLoading();
  53. }
  54. },
  55. fail: (err) => {
  56. // 请求失败处理
  57. uni.showToast({
  58. title: '出错了,请联系管理员~',
  59. icon: 'none'
  60. })
  61. reject(err);
  62. uni.hideLoading();
  63. },
  64. });
  65. });
  66. };