util.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. var api = require('../config/api.js');
  2. var app = getApp();
  3. function formatTime(date) {
  4. var year = date.getFullYear()
  5. var month = date.getMonth() + 1
  6. var day = date.getDate()
  7. var hour = date.getHours()
  8. var minute = date.getMinutes()
  9. var second = date.getSeconds()
  10. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  11. }
  12. function formatNumber(n) {
  13. n = n.toString()
  14. return n[1] ? n : '0' + n
  15. }
  16. /**
  17. * 封封微信的的request
  18. */
  19. function request(url, data = {}, method = "GET") {
  20. return new Promise(function(resolve, reject) {
  21. wx.request({
  22. url: url,
  23. data: data,
  24. method: method,
  25. header: {
  26. 'Content-Type': 'application/json',
  27. 'X-Litemall-Token': wx.getStorageSync('token')
  28. },
  29. success: function(res) {
  30. if (res.statusCode == 200) {
  31. if (res.data.errno == 501) {
  32. // 清除登录相关内容
  33. try {
  34. wx.removeStorageSync('userInfo');
  35. wx.removeStorageSync('token');
  36. } catch (e) {
  37. // Do something when catch error
  38. }
  39. // 切换到登录页面
  40. wx.navigateTo({
  41. url: '/pages/auth/login/login'
  42. });
  43. } else {
  44. resolve(res.data);
  45. }
  46. } else {
  47. reject(res.errMsg);
  48. }
  49. },
  50. fail: function(err) {
  51. reject(err)
  52. }
  53. })
  54. });
  55. }
  56. function redirect(url) {
  57. //判断页面是否需要登录
  58. if (false) {
  59. wx.redirectTo({
  60. url: '/pages/auth/login/login'
  61. });
  62. return false;
  63. } else {
  64. wx.redirectTo({
  65. url: url
  66. });
  67. }
  68. }
  69. function showErrorToast(msg) {
  70. wx.showToast({
  71. title: msg,
  72. image: '/static/images/icon_error.png'
  73. })
  74. }
  75. module.exports = {
  76. formatTime,
  77. request,
  78. redirect,
  79. showErrorToast
  80. }