ajax.service.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // if(options.isHost){
  30. // url = corServiceUrl + url
  31. // }else{
  32. // url = spiServiceUrl + url
  33. // }
  34. let { isLoading = true } = options
  35. if (isLoading) {
  36. uni.showLoading({ title: '加载中' })
  37. }
  38. const requestPromise = new Promise((resolve, reject) => {
  39. uni.request({
  40. url: url,
  41. method: options.method || 'POST',
  42. data: options.data || {},
  43. header,
  44. success: res => {
  45. if (isLoading) uni.hideLoading()
  46. if(options.isStatus){
  47. resolve(res.data)
  48. }else{
  49. if (res.data.code === 0) {
  50. resolve(res.data)
  51. } else {
  52. reject(res.data)
  53. }
  54. }
  55. },
  56. fail: error => {
  57. reject(error)
  58. if (isLoading) uni.hideLoading()
  59. }
  60. })
  61. })
  62. return requestPromise
  63. }
  64. get(options) {
  65. options.method = 'GET'
  66. return this.request(options)
  67. }
  68. post(options) {
  69. options.method = 'POST'
  70. return this.request(options)
  71. }
  72. }
  73. export default new AjaxService()