request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import define from './define'
  2. import {
  3. useLocale
  4. } from '@/locale/useLocale';
  5. const {
  6. getBackLocale
  7. } = useLocale();
  8. const host = define.baseURL
  9. const defaultOpt = {
  10. load: true
  11. }
  12. // 示例
  13. // async xxxx(code) {
  14. // var res = await this.request({
  15. // url: '/api/System/DictionaryData/All',
  16. // method: 'GET',
  17. // data,
  18. // options: {
  19. // load: false
  20. // }
  21. // })
  22. // if (!res) return
  23. // console.log(res)
  24. // }
  25. function request(config) {
  26. config.options = Object.assign(defaultOpt, config.options)
  27. const token = uni.getStorageSync('token') || ''
  28. const systemCode = uni.getStorageSync('systemCode') || ''
  29. const locale = getBackLocale()
  30. let header = {
  31. "App-Code": systemCode,
  32. "Content-Type": "application/json;charset=UTF-8",
  33. "Jnpf-Origin": "app",
  34. "Vue-Version": "3",
  35. "Accept-Language": locale,
  36. ...config.header
  37. }
  38. header['App-Code'] = encodeURIComponent(header['App-Code'])
  39. if (token) header['Authorization'] = token
  40. let url = config.url.indexOf('http') > -1 ? config.url : host + config.url
  41. if (config.options.load) {
  42. uni.showLoading({
  43. title: config.options.loadText || '正在加载'
  44. })
  45. }
  46. return new Promise((resolve, reject) => {
  47. uni.request({
  48. url: url,
  49. data: config.data || {},
  50. method: config.method || 'GET',
  51. header: header,
  52. timeout: define.timeout,
  53. success: res => {
  54. if (res.statusCode === 200) {
  55. if (res.data.code == 200) {
  56. resolve(res.data)
  57. } else {
  58. ajaxError(res.data)
  59. reject(res.data.msg)
  60. }
  61. } else {
  62. ajaxError(res.data)
  63. reject(res.errMsg)
  64. }
  65. uni.hideLoading();
  66. },
  67. fail: err => {
  68. uni.showToast({
  69. title: '连接服务器失败',
  70. icon: 'none',
  71. })
  72. setTimeout(function () {
  73. uni.hideLoading();
  74. }, 2000);
  75. reject(err)
  76. }
  77. })
  78. })
  79. }
  80. function ajaxError(data) {
  81. uni.showToast({
  82. title: data.msg || '请求出错,请重试',
  83. icon: 'none',
  84. complete() {
  85. if (data.code === 600 || data.code === 601 || data.code === 602) {
  86. setTimeout(() => {
  87. uni.removeStorageSync('token')
  88. uni.removeStorageSync('cid')
  89. uni.removeStorageSync('userInfo')
  90. uni.removeStorageSync('permissionList')
  91. uni.removeStorageSync('sysVersion')
  92. uni.removeStorageSync('dynamicModelExtra')
  93. uni.reLaunch({
  94. url: '/pages/login/index'
  95. })
  96. }, 1500)
  97. }
  98. }
  99. })
  100. }
  101. export default request