request.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.navigateTo({
  29. url: '/pages/login'
  30. })
  31. } else if (res.data.code == 6401) {
  32. uni.request({
  33. url: ENV.APP_DEV_URL + '/api/applet/refresh',
  34. method: 'GET',
  35. success: (res) => {
  36. console.log(res, 135)
  37. Storage.removeToken()
  38. }
  39. })
  40. } else {
  41. resolve(res)
  42. }
  43. } else {
  44. resolve(res)
  45. }
  46. },
  47. fail(res) {
  48. resolve(res)
  49. }
  50. }
  51. uni.request(param)
  52. }).catch((res) => {
  53. if (res.statusCode === 200) {
  54. if (res.data.code !== 200) {
  55. return res.data
  56. }
  57. } else {
  58. console.log('服务器错误:', res)
  59. return res;
  60. }
  61. })
  62. return promise
  63. }
  64. static get(url, data, that) {
  65. return this.request('GET', url, data, that)
  66. }
  67. static post(url, data, that) {
  68. return this.request('POST', url, data, that)
  69. }
  70. static put(url, data, that) {
  71. return this.request('PUT', url, data, that)
  72. }
  73. static delete(url, data, that) {
  74. return this.request('DELETE', url, data, that)
  75. }
  76. }
  77. export default request