http.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. // login()
  48. }
  49. },
  50. fail() {
  51. wx.showToast({
  52. title: '服务器异常 请稍后再试',
  53. icon: 'none'
  54. })
  55. }
  56. })
  57. }
  58. export function login(opts) {
  59. wx.login({
  60. success: res => {
  61. post('api/login',{
  62. js_code: res.code
  63. },(res) => {
  64. if(res.code == 200) {
  65. wx.setStorageSync('token', res.data.token);
  66. if(res.data.status == 1) {
  67. // wx.setStorageSync('userInfo', {
  68. // avatar_url: res.data.avatar_url,
  69. // mobile: res.data.mobile,
  70. // nickname: res.data.nickname,
  71. // uid: res.data.uid,
  72. // });
  73. getUser()
  74. }
  75. if(res.data.status == 0) {
  76. wx.reLaunch({
  77. url: '/pages/login/login',
  78. })
  79. // if(opts && opts.path == 'pages/deviceLogin/deviceLogin') {
  80. // wx.navigateTo({
  81. // url: '/pages/login/login',
  82. // })
  83. // } else {
  84. // wx.reLaunch({
  85. // url: '/pages/login/login',
  86. // })
  87. // }
  88. return;
  89. }
  90. }
  91. })
  92. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  93. }
  94. })
  95. }
  96. /**
  97. * 获取用户信息
  98. * api/user
  99. */
  100. function getUser() {
  101. get('api/user',{},(res) => {
  102. if(res.data) {
  103. wx.setStorageSync('userInfo',res.data);
  104. }
  105. console.log(res)
  106. })
  107. }