猎豆优选小程序

util.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. let BASE_URL = 'https://ld.726p.com' // 请求地址 - 生产环境
  2. // let BASE_URL = 'http://ld-test.wenxingshuju.com' // ceshi
  3. // let BASE_URL = 'http://60.205.169.65:8006' // 请求地址 - 测试环境
  4. // #ifdef H5
  5. BASE_URL = '' //线上模式
  6. // BASE_URL = '/api' // 开发模式
  7. // #endif
  8. const LOGIN_ERR_CODES = [ // 登录状态失效错误码
  9. '2008',
  10. '2005',
  11. '4001',
  12. '4002',
  13. ]
  14. const handleToLogin = () => {
  15. uni.clearStorageSync()
  16. uni.reLaunch({
  17. url: '/pages/subPackages/login/loginPhone'
  18. });
  19. }
  20. const req = (url, method, data, selfHeader) => {
  21. const dataes = {
  22. // 'ttl': uni.getStorageSync('ttl'),
  23. }
  24. const header = {
  25. 'source': uni.getStorageSync('channel_source') || '',
  26. 'version': uni.getStorageSync('channel_version') || '',
  27. // #ifdef H5
  28. 'source': '3002',
  29. 'version': 'v1.0',
  30. // #endif
  31. 'token': uni.getStorageSync('token') || '',
  32. }
  33. return new Promise((resolve, reject) => {
  34. uni.request({
  35. url:`${BASE_URL}${url}`,
  36. data: data ? Object.assign(dataes, data) : dataes,
  37. method: method,
  38. header: selfHeader ? Object.assign(header, selfHeader) : header,
  39. success: function (res) {
  40. if (LOGIN_ERR_CODES.includes(String(res.data.errno))) {
  41. handleToLogin()
  42. }
  43. resolve(res)
  44. },
  45. fail: function (err) {
  46. reject(err)
  47. }
  48. })
  49. })
  50. }
  51. const get = (url, data, header = {}) => {
  52. return req(url, 'GET', data, {
  53. ...header
  54. })
  55. }
  56. const post = (url, data, header = {}) => {
  57. return req(url, 'POST', data, {
  58. 'Content-Type': 'application/x-www-form-urlencoded',
  59. ...header,
  60. })
  61. }
  62. const postJSON = (url, data, header = {}) => {
  63. return req(url, 'POST', data, {
  64. 'Content-Type': 'application/json',
  65. ...header,
  66. })
  67. }
  68. // 获取随机参数 h5使用
  69. const getUuid = () => {
  70. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  71. const r = (Math.random() * 16) | 0,
  72. v = c == 'x' ? r : (r & 0x3) | 0x8
  73. return v.toString(16)
  74. })
  75. }
  76. export {
  77. req,
  78. BASE_URL,
  79. get,
  80. post,
  81. postJSON,
  82. getUuid,
  83. }