request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import * as config from '@/config'
  2. let baseUrl = config.def().baseUrlNew
  3. // 定义基础请求路径(后端服务器地址)
  4. const baseRequest = (_gp, _mt, data = {}, failCallback) => {
  5. //异步请求数据
  6. return new Promise(resolve => {
  7. // if (!userInfo || !userInfo.accessToken) {
  8. // userInfo = uni.getStorageSync('userInfo')
  9. // }
  10. // let accessToken = userInfo ? userInfo.accessToken : ''
  11. let baseUrl = config.def().baseUrlNew
  12. uni.request({
  13. url: baseUrl + '/m.api',
  14. data: {
  15. ...data,
  16. _gp,
  17. _mt
  18. },
  19. method: 'POST',
  20. header: {
  21. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  22. // 'ACCESSTOKEN': accessToken
  23. },
  24. success: (res) => {
  25. if (res.statusCode === 200) {
  26. if (res.data.errno === 200) {
  27. resolve(res.data);
  28. } else {
  29. if (failCallback) {
  30. failCallback(res.data)
  31. } else {
  32. uni.showToast({
  33. title: res.data.errmsg,
  34. icon: 'none'
  35. })
  36. }
  37. }
  38. }
  39. }
  40. })
  41. })
  42. }
  43. //带Token请求
  44. const TokenRequest = (method, url, data, header) => {
  45. var contentheader = 'application/json'
  46. if (header) {
  47. contentheader = header
  48. }
  49. let ac_token = "";
  50. uni.getStorage({
  51. key: 'userInfo',
  52. success: function(res) {
  53. ac_token = res.data.accessToken
  54. }
  55. });
  56. //此token是登录成功后后台返回保存在storage中的
  57. let DefaultOpts = {
  58. url: baseUrl + url,
  59. data: data,
  60. method: method,
  61. header: {
  62. 'content-type': contentheader,
  63. 'Token': ac_token,
  64. }
  65. }
  66. let promise = new Promise(function(resolve, reject) {
  67. uni.request(DefaultOpts).then(
  68. (res) => {
  69. console.log(JSON.stringify(res[1].data))
  70. if (res[1].data.code == '200' || res[1].data.code == 200) {
  71. // 后端返回的状态码100为成功状态,成功则返回请求结果,在app调试时可以通过console.log(JSON.stringify(res[1].data))来查看返回值(以项目实际情况为准)
  72. resolve(res[1].data)
  73. }
  74. if (res[1].data.code == '105' || res[1].data.code == 105) {
  75. // 后端返回状态码为105则为未登录状态(以项目实际情况为准)
  76. uni.showToast({
  77. icon: 'none',
  78. title: '尚未登录',
  79. duration: 2000
  80. });
  81. // 尚未登录的逻辑处理
  82. return false
  83. }
  84. }
  85. ).catch(
  86. (response) => {
  87. reject(response)
  88. }
  89. )
  90. })
  91. return promise
  92. }
  93. export default {
  94. baseUrl,
  95. baseRequest,
  96. TokenRequest
  97. }