restful.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = 'http://192.168.1.106:9901';
  8. //正式环境
  9. const HOST = 'http://wordpad-api-test.efunbox.cn';
  10. //API接口
  11. const interfaces = {
  12. //这里边放入请求的接口
  13. //根据userId获取用户信息
  14. getUserById: '/tch/user/getUserById'
  15. }
  16. function fun(url: String, type: any, data: any, otherType: any) {
  17. if (!TOKEN) {
  18. //这里可以做一个请求的拦截 看有没有携带token
  19. console.log("Token:", TOKEN)
  20. }
  21. let promise = new Promise((resolve, reject) => {
  22. wx.request({
  23. url: HOST + url,
  24. method: type,
  25. data: type == 'GET' ? data : JSON.stringify(data),
  26. header: {
  27. 'content-type': otherType ? APPLICATION_JSON_UTF8_FORM : APPLICATION_JSON_UTF8_VALUE,
  28. 'access-token': wx.getStorageSync('accessToken') == null ? '' : wx.getStorageSync('accessToken'),
  29. 'userId': TOKEN
  30. },
  31. success: function (res: any) {
  32. wx.stopPullDownRefresh();
  33. if (res) {
  34. resolve(res)
  35. } else {
  36. wx.showToast({
  37. title: res.data.subMsg ? res.data.subMsg : res.data.msg,
  38. icon: 'none',
  39. duration: 2000
  40. })
  41. }
  42. },
  43. fail: function (res: any) {
  44. wx.stopPullDownRefresh();
  45. reject(res)
  46. }
  47. })
  48. })
  49. return promise
  50. }
  51. export const httpUtil = {
  52. interfaces,
  53. wxGet: function (url: String, data: any) {
  54. return fun(url, 'GET', data, null)
  55. },
  56. wxPost: function (url: String, data: any) {
  57. return fun(url, 'POST', data, null)
  58. },
  59. wxFormPost: function (url: String, data: any) {
  60. return fun(url, 'POST', data, 'formPost')
  61. },
  62. wxPut: function (url: String, data: any) {
  63. return fun(url, 'PUT', data, null)
  64. },
  65. wxDel: function (url: String, data: any) {
  66. return fun(url, 'DELETE', data, null)
  67. }
  68. }