http.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. export let api_url = null;
  2. export function get(url,params, success = noop, fail = noop) {
  3. return http(url,'GET',params, success,fail)
  4. }
  5. export function post(url,params, success = noop, fail = noop) {
  6. return http(url,'POST',params, success,fail)
  7. }
  8. function noop() {}
  9. function http(url,method,params, success, fail) {
  10. const type = wx.getStorageSync('env') || 'dev'; // 测试环境
  11. // const type = wx.getStorageSync('env') || 'ijolijoli'; // 正式环境
  12. switch(type) {
  13. case 'dev':
  14. api_url = 'https://store.test-api.ijolijoli.com/'
  15. break;
  16. default:
  17. api_url = 'https://api.ijolijoli.com/'
  18. break;
  19. }
  20. return wx.request({
  21. url: `${api_url}${url}`,
  22. method: method,
  23. data: params,
  24. header: {
  25. token: wx.getStorageSync('token') || '',
  26. },
  27. success: ({
  28. data,
  29. statusCode,
  30. header
  31. }) => {
  32. console.log(`==============${url}`,data)
  33. if(data.code == 200) {
  34. success(data, header);
  35. } else if(data.code == 201) {
  36. wx.showToast({
  37. title: data.msg,
  38. icon: 'none'
  39. })
  40. fail(data, header)
  41. } else if(data.code == 400) {
  42. console.log('登录失败')
  43. wx.showToast({
  44. title: data.msg,
  45. icon: 'none'
  46. })
  47. wx.reLaunch({
  48. url: '/pages/login/login',
  49. })
  50. // login()
  51. }
  52. },
  53. fail() {
  54. wx.showToast({
  55. title: '服务器异常 请稍后再试',
  56. icon: 'none'
  57. })
  58. }
  59. })
  60. }
  61. export function login(opts) {
  62. wx.login({
  63. success: res => {
  64. post('api/login',{
  65. js_code: res.code
  66. },(res) => {
  67. if(res.code == 200) {
  68. wx.setStorageSync('token', res.data.token);
  69. if(res.data.status == 1) {
  70. // wx.setStorageSync('userInfo', {
  71. // avatar_url: res.data.avatar_url,
  72. // mobile: res.data.mobile,
  73. // nickname: res.data.nickname,
  74. // uid: res.data.uid,
  75. // });
  76. getUser()
  77. }
  78. if(res.data.status == 0) {
  79. wx.reLaunch({
  80. url: '/pages/login/login',
  81. })
  82. // if(opts && opts.path == 'pages/deviceLogin/deviceLogin') {
  83. // wx.navigateTo({
  84. // url: '/pages/login/login',
  85. // })
  86. // } else {
  87. // wx.reLaunch({
  88. // url: '/pages/login/login',
  89. // })
  90. // }
  91. return;
  92. }
  93. }
  94. })
  95. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  96. }
  97. })
  98. }
  99. /**
  100. * 获取用户信息
  101. * api/user
  102. */
  103. function getUser() {
  104. get('api/user',{},(res) => {
  105. if(res.data) {
  106. wx.setStorageSync('userInfo',res.data);
  107. }
  108. console.log(res)
  109. })
  110. }