ajax.service.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import spiServiceUrl from './ajax.env'
  5. import corServiceUrl from './config.env'
  6. import { msg } from '@/utils/util'
  7. class AjaxService {
  8. constructor() {
  9. this.name = 'AjaxService'
  10. }
  11. getBaseUrl (url = '') {
  12. return url.indexOf('://') > -1 ? url : url
  13. }
  14. getHeaders({ header = {} }) {
  15. const REV_TOKEN_ENV = uni.getStorageSync('token') ? uni.getStorageSync('token') : 'X-token';
  16. const REV_COOKIE_ENV = uni.getStorageSync('sessionid') ? uni.getStorageSync('sessionid') : 'sessionid';
  17. header['Accept'] = 'application/json'
  18. header['Content-Type'] = 'application/x-www-form-urlencoded'
  19. header['X-Token'] = REV_TOKEN_ENV
  20. header['cookie'] = REV_COOKIE_ENV
  21. return header
  22. }
  23. request(options = {}) {
  24. let header = this.getHeaders(options)
  25. let url = this.getBaseUrl(options.url)
  26. if (options.header) {
  27. header = Object.assign(header, options.header)
  28. }
  29. if(options.isHost){
  30. url = corServiceUrl + url
  31. }else{
  32. url = spiServiceUrl + url
  33. }
  34. let { isLoading = true } = options
  35. if (isLoading) {
  36. wx.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) wx.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. wx.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()