request.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import config from '@/config'
  2. import {
  3. getToken,
  4. getServerUrl
  5. } from '@/utils/auth'
  6. import errorCode from '@/utils/errorCode'
  7. import {
  8. toast,
  9. showConfirm,
  10. tansParams
  11. } from '@/utils/common'
  12. let timeout = 10000
  13. const baseUrl = config.baseUrl
  14. const request = config => {
  15. // 是否需要设置 token
  16. const isToken = (config.headers || {}).isToken === false
  17. config.header = config.header || {}
  18. // if (getToken() && !isToken) {
  19. // // config.header['Authorization'] = 'Bearer ' + getToken()
  20. // config.header['UserKey'] = getToken()
  21. // config.header['ServerUrl'] = getServerUrl()
  22. // } else {
  23. // uni.reLaunch({
  24. // url: '/pages/index/login'
  25. // })
  26. // }
  27. // get请求映射params参数
  28. if (config.params) {
  29. let url = config.url + '?' + tansParams(config.params)
  30. url = url.slice(0, -1)
  31. config.url = url
  32. }
  33. const xml2js = require('xml2js');
  34. return new Promise((resolve, reject) => {
  35. uni.request({
  36. method: config.method || 'get',
  37. timeout: config.timeout || timeout,
  38. url: config.baseUrl || baseUrl + config.url,
  39. data: config.data,
  40. header: config.header,
  41. dataType: 'json',
  42. success: res => {
  43. if(res.statusCode == 200){
  44. xml2js.parseString(res.data, (err, result) => {
  45. if (err) {
  46. reject(err);
  47. }
  48. // 解析后的结果保存在result中
  49. const jsonResult = JSON.parse(result.string._);
  50. resolve(jsonResult)
  51. // if(jsonResult.flag){
  52. // resolve(jsonResult.result)
  53. // }else{
  54. // reject(jsonResult.message)
  55. // }
  56. });
  57. }else{
  58. reject("获取数据失败!")
  59. }
  60. },
  61. fail: err => {
  62. reject(err)
  63. },
  64. complete: () => {
  65. //uni.hideLoading()
  66. }
  67. })
  68. })
  69. }
  70. export default request