ajax.service.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. console.log('2222222222')
  51. resolve(res.data)
  52. } else {
  53. reject(res.data)
  54. }
  55. }
  56. },
  57. fail: error => {
  58. reject(error)
  59. wx.hideLoading()
  60. }
  61. })
  62. })
  63. return requestPromise
  64. }
  65. get(options) {
  66. options.method = 'GET'
  67. return this.request(options)
  68. }
  69. post(options) {
  70. options.method = 'POST'
  71. return this.request(options)
  72. }
  73. }
  74. export default new AjaxService()