request.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. Storage.removeToken()
  33. } else {
  34. resolve(res)
  35. }
  36. } else {
  37. resolve(res)
  38. }
  39. },
  40. fail(res) {
  41. resolve(res)
  42. }
  43. }
  44. uni.request(param)
  45. }).catch((res) => {
  46. if (res.statusCode === 200) {
  47. if (res.data.code !== 200) {
  48. return res.data
  49. }
  50. } else {
  51. console.log('服务器错误:', res)
  52. return res;
  53. }
  54. })
  55. return promise
  56. }
  57. static get(url, data, that) {
  58. return this.request('GET', url, data, that)
  59. }
  60. static post(url, data, that) {
  61. return this.request('POST', url, data, that)
  62. }
  63. static put(url, data, that) {
  64. return this.request('PUT', url, data, that)
  65. }
  66. static delete(url, data, that) {
  67. return this.request('DELETE', url, data, that)
  68. }
  69. }
  70. export default request