http.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {wxToPromise} from "./wx";
  2. import config from "../model/config";
  3. import Route from "../model/route";
  4. import User from "../model/user";
  5. import {showLoading} from "./utils";
  6. const app = getApp();
  7. class Http {
  8. static async request({url, data, method = 'get', opt = {isLoading: false}}) {
  9. const isLoading = opt.isLoading;
  10. if (isLoading) {
  11. showLoading();
  12. }
  13. let res
  14. try {
  15. let tokenObj = {};
  16. if (app.globalData.token) {
  17. tokenObj.Authorization = app.globalData.token;
  18. }
  19. res = await wxToPromise('request', {
  20. url: `${config.API}${url}`,
  21. data,
  22. method,
  23. header: {
  24. 'content-type': 'application/json',
  25. ...tokenObj
  26. }
  27. })
  28. } catch (e) {
  29. console.log('网络错误', e);
  30. // 代码逻辑异常、无网络、请求超时会走这里
  31. Http._showError(-100)
  32. throw new Error(e.errMsg)
  33. }
  34. if (isLoading) {
  35. wx.hideLoading()
  36. }
  37. if (res.statusCode == 200) {
  38. if (res.data.code == 200) {
  39. console.log(`网络请求${url}`, data, res.data);
  40. return res.data;
  41. } else if (res.data.code == 401) {
  42. Route.toLogin();
  43. User.logout();
  44. } else if (res.data.code == 511) {//针对提交 重复的,直接判断为成功,但是结果不会存在了
  45. console.log(`网络请求${url}重复提交`, data, res.data);
  46. return res.data;
  47. } else {
  48. Http._showError(res.data.code, res.data.msg)
  49. throw new Error(res.data.msg)
  50. }
  51. } else {
  52. Http._showError(res.statusCode)
  53. throw new Error(res.statusCode)
  54. }
  55. }
  56. static _showError(errorCode, message = '') {
  57. const errorMessage = config.ERROR_MSG[errorCode];
  58. const title = errorMessage || message || '未知异常'
  59. console.log("错误提示", title)
  60. wx.showToast({
  61. title,
  62. icon: 'none',
  63. duration: 3000
  64. })
  65. }
  66. }
  67. export default Http