ajax.service.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import requestUrl from '@/services/config.env.js'
  5. import { msg } from '@/utils/util'
  6. class AjaxService {
  7. constructor() {
  8. this.name = 'AjaxService'
  9. }
  10. getBaseUrl (url = '') {
  11. return url.indexOf('://') > -1 ? url : url
  12. }
  13. getHeaders({ header = {} }) {
  14. const REV_TOKEN_ENV = uni.getStorageSync('token') ? uni.getStorageSync('token') : 'X-token'
  15. const REV_COOKIE_ENV = uni.getStorageSync('sessionid') ? uni.getStorageSync('sessionid') : 'sessionid'
  16. header['Accept'] = 'application/json'
  17. header['Content-Type'] = 'application/x-www-form-urlencoded'
  18. header['X-Token'] = REV_TOKEN_ENV
  19. header['cookie'] = REV_COOKIE_ENV
  20. return header
  21. }
  22. request(options = {}) {
  23. let header = this.getHeaders(options)
  24. let url = this.getBaseUrl(options.url)
  25. if (options.header) {
  26. header = Object.assign(header, options.header)
  27. }
  28. url = requestUrl + url
  29. let { isLoading = true } = options
  30. if (isLoading) {
  31. uni.showLoading({ title: options.loadText ? options.loadText : '加载中' })
  32. }
  33. const requestPromise = new Promise((resolve, reject) => {
  34. uni.request({
  35. url: url,
  36. method: options.method || 'POST',
  37. data: options.data || {},
  38. header,
  39. success: res => {
  40. if (isLoading) uni.hideLoading()
  41. if(options.isStatus){
  42. resolve(res.data)
  43. }else{
  44. if (res.data.code === 0) {
  45. resolve(res.data)
  46. } else {
  47. reject(res.data)
  48. }
  49. }
  50. },
  51. fail: error => {
  52. reject(error)
  53. if (isLoading) uni.hideLoading()
  54. }
  55. })
  56. })
  57. return requestPromise
  58. }
  59. get(options) {
  60. options.method = 'GET'
  61. return this.request(options)
  62. }
  63. post(options) {
  64. options.method = 'POST'
  65. return this.request(options)
  66. }
  67. }
  68. export default new AjaxService()