Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

87 rader
2.1 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. uni.showToast({ title: msg || '请求失败', icon: 'none' })
  45. return Promise.reject({ code, msg: msg || '请求失败' })
  46. },
  47. (error) => {
  48. uni.showToast({ title: '网络请求失败', icon: 'none' })
  49. return Promise.reject({ code: -1, msg: error.errMsg || '网络请求失败' })
  50. }
  51. )
  52. }
  53. export function get(url, params = {}, config = {}) {
  54. return uni.$u.http.get(url, { params, ...config })
  55. }
  56. export function post(url, data = {}, config = {}) {
  57. return uni.$u.http.post(url, data, config)
  58. }
  59. export function put(url, data = {}, config = {}) {
  60. return uni.$u.http.put(url, data, config)
  61. }
  62. export function del(url, data = {}, config = {}) {
  63. return uni.$u.http.delete(url, { data, ...config })
  64. }
  65. export function upload(url, { filePath, name = 'file', formData = {} } = {}) {
  66. return uni.$u.http.upload(url, { filePath, name, formData })
  67. }
  68. export function download(url, config = {}) {
  69. return uni.$u.http.download(url, config)
  70. }
  71. export default { get, post, put, del, upload, download }