api.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* 请求的错误不应该被调用方被catch
  2. 把错误的请求当成请求正常返回的结果
  3. 由调用方根据状态码来判断是否成功 */
  4. var base64 = require('/base64');
  5. const app = getApp();
  6. const config = require('../config/config.js');
  7. const constants = require('../utils/Constants');
  8. /* 服务端IP+端口 */
  9. export const API_URI = (app && app.globalData && app.globalData.URI) ? app.globalData.URI : (config.server_add + ':' + config.server_port)
  10. /* 调用的请求方法 */
  11. function request(url, requestType, params) {
  12. return new Promise((resolve, reject) => {
  13. wxRequest(url, requestType, params).then(res => {
  14. console.log('[请求地址]:', url,
  15. '\n[请求参数]:', params,
  16. '\n[响应状态]:', res.data.code,
  17. '\n[响应数据]:', res.data.data,
  18. '\n[响应信息]:', res.data.message,
  19. '\n[异常信息]:', res.data.exception)
  20. switch (res.data.code) {
  21. case 200:
  22. break;
  23. case 1015://1015 当前用户未注册 2022年11月14日
  24. break;
  25. case -2: case -4: case 233:
  26. wx.showModal({
  27. title: '提示', content: res.data.message, showCancel: false,
  28. success: function (res) {
  29. wx.navigateTo({
  30. url: '/pages/login/login',
  31. })
  32. }
  33. });
  34. break;
  35. default:
  36. if (res.data.exception) {
  37. wx.showModal({
  38. title: '提示', content: res.data.message, cancelText: '日志',
  39. success(res_model) {
  40. if (res_model.cancel) {
  41. wx.showModal({ title: '异常信息', content: res.data.exception, showCancel: false });
  42. }
  43. }
  44. });
  45. } else {
  46. wx.showModal({ title: '提示', content: res.data.message, showCancel: false });
  47. }
  48. break;
  49. }
  50. resolve(res)
  51. }).catch(err => {
  52. resolve({ code: -200, message: "请求失败", data: err });
  53. })
  54. })
  55. }
  56. /* 封装wx.request */
  57. function wxRequest(url, requestType, params) {
  58. return new Promise((resolve, reject) => {
  59. let app = getApp(), header = {
  60. 'content-type': 'application/json'
  61. }
  62. var openId = app.globalData.openid
  63. if (app.globalData.user) {
  64. app.globalData.user.openId = openId
  65. // 请求的Authorization
  66. header['Authorization'] = "Bearer " + app.globalData.token
  67. }
  68. // 语言
  69. header['i18n'] = constants.lan
  70. if (app && app.globalData && app.globalData.company && app.globalData.company.svcCode) {
  71. url = url.replace('mdm-server', 'mdm-server' + '-' + app.globalData.company.svcCode.replace('_', '-'))
  72. }
  73. wx.request({
  74. url: `${API_URI}/${url}`,
  75. header: header,
  76. data: params ? params : null,
  77. method: requestType ? requestType : 'POST',
  78. success: function (res) {
  79. resolve(res);
  80. },
  81. fail: function (err) {
  82. reject(err);
  83. }
  84. })
  85. })
  86. }
  87. /* 暴露方法给外部 */
  88. module.exports = {
  89. request
  90. }