request.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import config from "@/config";
  2. import store from "../store";
  3. import chat from '@/uitls/chat.js'
  4. const logout = () => {
  5. chat.disConnect();
  6. uni.removeStorageSync('token');
  7. uni.removeStorageSync('chatToken');
  8. uni.removeStorageSync('vuex_state');
  9. store.dispatch('app/changeOrganization', {});
  10. store.dispatch('app/changeUser', {});
  11. uni.removeTabBarBadge({
  12. index: 3
  13. })
  14. }
  15. /* 消息提示 */
  16. const tip = (msg) => {
  17. let types = 'warning';
  18. if (msg == 'RET_INVALID_PASSWORD') msg = '账号密码有误'
  19. if (msg == 'RET_INVALID_CODE') msg = '短信验证码有误'
  20. if (msg == 'RET_AUTH_FAILED') {
  21. logout();
  22. let pageList = getCurrentPages();
  23. if (pageList[pageList.length - 1].route !== 'pages/login/login') {
  24. setTimeout(() => {
  25. uni.navigateTo({
  26. url: '/pages/login/login'
  27. });
  28. }, 400)
  29. }
  30. msg = '登录已过期,请重新登录'
  31. }
  32. uni.showToast({
  33. title: msg,
  34. icon: 'none'
  35. })
  36. }
  37. const errorCallBack = (resolve) => {
  38. // 请求失败处理
  39. tip('出错了,请联系系统管理员~');
  40. resolve({
  41. state: false,
  42. data: null,
  43. msg: 'error'
  44. });
  45. uni.hideLoading();
  46. }
  47. export function request(options) {
  48. return new Promise((resolve, reject) => {
  49. let header = options.header || {
  50. 'Content-Type': 'application/json'
  51. }
  52. if (uni.getStorageSync('token')) header['token'] = uni.getStorageSync('token');
  53. uni.request({
  54. url: config.baseUrl + options.url, // 服务器url
  55. method: options.method || 'GET', // 请求方法,默认为GET
  56. data: options.data || {}, // 请求参数
  57. header: header, // 设置请求的 header
  58. success: (res) => {
  59. // 请求成功
  60. if (res.statusCode === 200) {
  61. let data = res.data;
  62. if (data.code != '200') {
  63. tip(data.message || data.msg);
  64. uni.hideLoading();
  65. }
  66. resolve({
  67. state: data.code == '200',
  68. data: data.data,
  69. msg: data.code == '200' ? 'success' : 'error'
  70. });
  71. } else {
  72. errorCallBack(resolve);
  73. }
  74. },
  75. fail: () => errorCallBack(resolve)
  76. });
  77. });
  78. };