Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

92 Zeilen
2.3 KiB

  1. /**
  2. * uview-plus http 请求配置
  3. */
  4. import { getToken, clearAll } from './cache.js'
  5. import envConfig from '@/config/env.js'
  6. const BASE_URL = envConfig.BASE_URL
  7. const CODE = {
  8. SUCCESS: 0,
  9. NEED_LOGIN: 1009
  10. }
  11. export function initRequest(http) {
  12. http.setConfig((config) => {
  13. config.baseURL = BASE_URL
  14. config.timeout = 20000
  15. config.header = {
  16. 'Content-Type': 'application/json'
  17. }
  18. return config
  19. })
  20. http.interceptors.request.use(
  21. (config) => {
  22. const token = getToken()
  23. if (token) {
  24. config.header.Authorization = `Bearer ${token}`
  25. }
  26. return config
  27. },
  28. (error) => Promise.reject(error)
  29. )
  30. http.interceptors.response.use(
  31. (response) => {
  32. const { code, data, list, msg } = response.data
  33. if (code === CODE.SUCCESS) {
  34. return { code, data, list, msg }
  35. }
  36. if (code === CODE.NEED_LOGIN) {
  37. clearAll()
  38. uni.showToast({ title: msg || '请先登录', icon: 'none' })
  39. setTimeout(() => {
  40. uni.reLaunch({ url: '/pages/login/index' })
  41. }, 1500)
  42. return Promise.reject({ code, msg: msg || '请先登录' })
  43. }
  44. // 1010: 需要前端确认的场景,不自动弹toast,由业务层处理
  45. if (code === 1010) {
  46. return Promise.reject({ code, data, msg: msg || '' })
  47. }
  48. uni.showToast({ title: msg || '请求失败', icon: 'none' })
  49. return Promise.reject({ code, msg: msg || '请求失败' })
  50. },
  51. (error) => {
  52. uni.showToast({ title: '网络请求失败', icon: 'none' })
  53. return Promise.reject({ code: -1, msg: error.errMsg || '网络请求失败' })
  54. }
  55. )
  56. }
  57. export function get(url, params = {}, config = {}) {
  58. return uni.$u.http.get(url, { params, ...config })
  59. }
  60. export function post(url, data = {}, config = {}) {
  61. return uni.$u.http.post(url, data, config)
  62. }
  63. export function put(url, data = {}, config = {}) {
  64. return uni.$u.http.put(url, data, config)
  65. }
  66. export function del(url, data = {}, config = {}) {
  67. return uni.$u.http.delete(url, { data, ...config })
  68. }
  69. export function upload(url, { filePath, name = 'file', formData = {} } = {}) {
  70. return uni.$u.http.upload(url, { filePath, name, formData })
  71. }
  72. export function download(url, config = {}) {
  73. return uni.$u.http.download(url, config)
  74. }
  75. export default { get, post, put, del, upload, download }