request.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import Storage from './../store/storage.js';
  2. const ENV = require('./../.env.js')
  3. const HttpCodes = {
  4. UNAUTHORIZED: 401, //登录失效
  5. }
  6. class request {
  7. static request(method, url, data = null, that = null) {
  8. let promise = new Promise(function(resolve, reject) {
  9. let _url
  10. if (process.env.NODE_ENV !== 'production') {
  11. _url = ENV.APP_DEV_URL + url
  12. } else {
  13. _url = ENV.APP_PROD_URL + url
  14. }
  15. const param = {
  16. url: _url,
  17. method: method,
  18. data: data,
  19. header: {
  20. 'Authorization': 'Bearer ' + Storage.getToken(),
  21. 'Content-Type': 'application/json',
  22. },
  23. success(res) {
  24. if (res.statusCode === 200) {
  25. if (res.data.code === 200) {
  26. resolve(res.data)
  27. } else if (res.data.code == 401) {
  28. uni.reLaunch({
  29. url: '/pages/login'
  30. })
  31. } else if (res.data.code == 6401) {
  32. uni.request({
  33. url: ENV.APP_PROD_URL + '/api/refresh_token',
  34. method: 'GET',
  35. header: {
  36. 'Authorization': 'Bearer ' + Storage.getToken(),
  37. 'Content-Type': 'application/json',
  38. },
  39. }).then(res => {
  40. if (res.data.code == 200) {
  41. Storage.setToken(res.data.token)
  42. param.header.Authorization = 'Bearer ' + res.data.token
  43. uni.request(param)
  44. } else if (res.data.code == 401) {
  45. Storage.removeToken()
  46. Storage.removeCache('userInfo')
  47. uni.redirectTo({
  48. url: '/pages/login'
  49. })
  50. }
  51. })
  52. } else {
  53. resolve(res)
  54. }
  55. } else {
  56. resolve(res)
  57. }
  58. },
  59. fail(res) {
  60. resolve(res)
  61. }
  62. }
  63. uni.request(param)
  64. }).catch((res) => {
  65. if (res.statusCode === 200) {
  66. if (res.data.code !== 200) {
  67. return res.data
  68. }
  69. } else {
  70. console.log('服务器错误:', res)
  71. return res;
  72. }
  73. })
  74. return promise
  75. }
  76. static get(url, data, that) {
  77. return this.request('GET', url, data, that)
  78. }
  79. static post(url, data, that) {
  80. return this.request('POST', url, data, that)
  81. }
  82. static put(url, data, that) {
  83. return this.request('PUT', url, data, that)
  84. }
  85. static delete(url, data, that) {
  86. return this.request('DELETE', url, data, that)
  87. }
  88. }
  89. export default request