restful.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
  2. const APPLICATION_JSON_UTF8_FORM = 'application/x-www-form-urlencoded;charset=UTF-8';
  3. const RESPONSE_OK = 20000;
  4. const TOKEN_BEOVERDUE = 40001;
  5. const TOKEN = wx.getStorageSync('accessToken') == null ? '' : wx.getStorageSync('accessToken');
  6. //测试环境
  7. const HOST = 'https://wordpad-api-test.efunbox.cn';
  8. //正式环境
  9. // const HOST = 'https://wordpad-api-test.efunbox.cn';
  10. const httpData = {
  11. userId: 'test'
  12. }
  13. //API接口
  14. const interfaces = {
  15. //这里边放入请求的接口
  16. //获取全国地址
  17. getOrganizeAll:'/organize/all',
  18. //获取学校信息和班级信息(根据type判断)
  19. getSchoolOrClass:'/school',
  20. //手机号登录注册
  21. phoneRegister: '/tch/user/register',
  22. //账号密码登录
  23. pwdPhoneLogin: '/tch/user/login',
  24. //根据userId获取用户信息
  25. getUserById: '/tch/user/getUserById'
  26. }
  27. function fun(url: String, type: any, data: any, otherType: any) {
  28. if (!TOKEN) {
  29. //这里可以做一个请求的拦截 看有没有携带token
  30. console.log("Token:", TOKEN)
  31. }
  32. let promise = new Promise((resolve, reject) => {
  33. wx.request({
  34. url: HOST + url,
  35. method: type,
  36. data: type == 'GET' ? data : JSON.stringify(data),
  37. header: {
  38. 'content-type': otherType ? APPLICATION_JSON_UTF8_FORM : APPLICATION_JSON_UTF8_VALUE,
  39. 'access-token': wx.getStorageSync('accessToken') == null ? '' : wx.getStorageSync('accessToken'),
  40. 'userId': httpData.userId
  41. },
  42. success: function (res: any) {
  43. wx.stopPullDownRefresh();
  44. if (res) {
  45. resolve(res)
  46. } else {
  47. wx.showToast({
  48. title: res.data.subMsg ? res.data.subMsg : res.data.msg,
  49. icon: 'none',
  50. duration: 2000
  51. })
  52. }
  53. },
  54. fail: function (res: any) {
  55. wx.stopPullDownRefresh();
  56. reject(res)
  57. }
  58. })
  59. })
  60. return promise
  61. }
  62. export const httpUtil = {
  63. httpData,
  64. interfaces,
  65. wxGet: function (url: String, data: any) {
  66. return fun(url, 'GET', data, null)
  67. },
  68. wxPost: function (url: String, data: any) {
  69. return fun(url, 'POST', data, null)
  70. },
  71. wxFormPost: function (url: String, data: any) {
  72. return fun(url, 'POST', data, 'formPost')
  73. },
  74. wxPut: function (url: String, data: any) {
  75. return fun(url, 'PUT', data, null)
  76. },
  77. wxDel: function (url: String, data: any) {
  78. return fun(url, 'DELETE', data, null)
  79. }
  80. }