request.js 2.1 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.clearStorageSync();
  7. store.dispatch('app/changeOrganization', {});
  8. store.dispatch('app/changeUser', {});
  9. uni.removeTabBarBadge({
  10. index: 3
  11. })
  12. }
  13. /* 消息提示 */
  14. const tip = (msg) => {
  15. let types = 'warning';
  16. if (msg == 'RET_INVALID_PASSWORD') msg = '账号密码有误'
  17. if (msg == 'RET_INVALID_CODE') msg = '短信验证码有误'
  18. if (msg == 'RET_AUTH_FAILED') {
  19. logout();
  20. let pageList = getCurrentPages();
  21. if (pageList[pageList.length - 1].route !== 'pages/login/login') {
  22. setTimeout(() => {
  23. uni.navigateTo({
  24. url: '/pages/login/login'
  25. });
  26. }, 400)
  27. }
  28. msg = '登录已过期,请重新登录'
  29. }
  30. uni.showToast({
  31. title: msg,
  32. icon: 'none'
  33. })
  34. }
  35. const errorCallBack = (resolve) => {
  36. // 请求失败处理
  37. tip('出错了,请联系系统管理员~');
  38. resolve({
  39. state: false,
  40. data: null,
  41. msg: 'error'
  42. });
  43. uni.hideLoading();
  44. }
  45. export function request(options) {
  46. return new Promise((resolve, reject) => {
  47. let header = options.header || {
  48. 'Content-Type': 'application/json'
  49. }
  50. if (uni.getStorageSync('token')) header['token'] = uni.getStorageSync('token');
  51. if (uni.getStorageSync('shopMobileToken')) header['authorization'] = uni.getStorageSync(
  52. 'shopMobileToken');
  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. };