http.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import baseUrl from '../utils/env'
  2. const http = (data) => {
  3. var data = Object.assign({}, {
  4. url: '',
  5. method: 'POST',
  6. data: {},
  7. success: null,
  8. error: null,
  9. loadTitle: '加载中',
  10. showLoading: true
  11. }, data)
  12. if (data.showLoading) {
  13. wx.showLoading({
  14. title: data.loadTitle,
  15. })
  16. }
  17. var userinfo = wx.getStorageSync('sg-userinfo')
  18. var token = userinfo ? userinfo.token : ''
  19. wx.request({
  20. url: baseUrl + data.url,
  21. method: data.method,
  22. data: data.data,
  23. header: {
  24. 'X-Token': token
  25. },
  26. success: function (res) {
  27. if (data.showLoading) wx.hideLoading()
  28. if (res.statusCode != 200) {
  29. wx.showToast({
  30. title: res.data.message,
  31. icon: 'none'
  32. })
  33. return false
  34. }
  35. if (res.data.code != 0) {
  36. wx.showToast({
  37. title: res.data.msg,
  38. icon: 'none'
  39. })
  40. if (res.data.code == -100) {
  41. var url = getCurrentUrl()
  42. if (url != 'pages/login/index') {
  43. wx.navigateTo({
  44. url: '/pages/login/index',
  45. })
  46. }
  47. }
  48. }
  49. typeof data.success === "function" && data.success(res.data)
  50. },
  51. fail: function (res) {
  52. console.log(res)
  53. typeof data.error === "function" && data.error(res.data)
  54. }
  55. })
  56. }
  57. const getCurrentUrl = () => {
  58. var pages = getCurrentPages()
  59. var page = pages[pages.length - 1]
  60. return page.route
  61. }
  62. module.exports = http