request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 locale = getBackLocale()
  29. let header = {
  30. "Content-Type": "application/json;charset=UTF-8",
  31. "jnpf-origin": "app",
  32. "vue-version": "3",
  33. "Accept-Language": locale,
  34. ...config.header
  35. }
  36. if (token) header['Authorization'] = token
  37. let url = config.url.indexOf('http') > -1 ? config.url : host + config.url
  38. if (config.options.load) {
  39. uni.showLoading({
  40. title: config.options.loadText || '正在加载'
  41. })
  42. }
  43. return new Promise((resolve, reject) => {
  44. uni.request({
  45. url: url,
  46. data: config.data || null,
  47. method: config.method || 'GET',
  48. header: header,
  49. timeout: define.timeout,
  50. success: res => {
  51. uni.hideLoading()
  52. if (res.statusCode === 200) {
  53. if (res.data.code == 200) {
  54. resolve(res.data)
  55. } else {
  56. ajaxError(res.data)
  57. reject(res.data.msg)
  58. }
  59. } else {
  60. ajaxError(res.data)
  61. reject(res.errMsg)
  62. }
  63. },
  64. fail: err => {
  65. uni.showToast({
  66. title: '连接服务器失败',
  67. icon: 'none',
  68. })
  69. uni.hideLoading()
  70. reject(err)
  71. }
  72. })
  73. })
  74. }
  75. function ajaxError(data) {
  76. uni.showToast({
  77. title: data.msg || '请求出错,请重试',
  78. icon: 'none',
  79. complete() {
  80. if (data.code === 600 || data.code === 601 || data.code === 602) {
  81. setTimeout(() => {
  82. uni.removeStorageSync('token')
  83. uni.removeStorageSync('cid')
  84. uni.removeStorageSync('userInfo')
  85. uni.removeStorageSync('permissionList')
  86. uni.removeStorageSync('sysVersion')
  87. uni.removeStorageSync('dynamicModelExtra')
  88. uni.reLaunch({
  89. url: '/pages/login/index'
  90. })
  91. }, 1500)
  92. }
  93. }
  94. })
  95. }
  96. export default request