request.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const BASE_URL = import.meta.env.VITE_API_BASE_URL
  2. const request = (url, method = 'GET', data = {}, options = {}) => {
  3. const {
  4. showLoading = true,
  5. loadingText = '加载中...',
  6. customHeaders = {}
  7. } = options
  8. const token = uni.getStorageSync('token')
  9. if (showLoading) {
  10. uni.showLoading({ title: loadingText, mask: true })
  11. }
  12. return new Promise((resolve, reject) => {
  13. uni.request({
  14. url: BASE_URL + url,
  15. method,
  16. data,
  17. header: {
  18. 'Content-Type': 'application/json',
  19. 'Authorization': token ? `Bearer ${token}` : '',
  20. ...customHeaders
  21. },
  22. success: res => {
  23. if (res.statusCode === 200) {
  24. resolve(res.data)
  25. } else {
  26. uni.showToast({
  27. title: res.data?.message || '请求出错',
  28. icon: 'none'
  29. })
  30. reject(res)
  31. }
  32. },
  33. fail: err => {
  34. uni.showToast({
  35. title: '网络异常,请稍后重试',
  36. icon: 'none'
  37. })
  38. reject(err)
  39. },
  40. complete: () => {
  41. if (showLoading) {
  42. uni.hideLoading()
  43. }
  44. }
  45. })
  46. })
  47. }
  48. export const get = (url, data = {}, options = {}) => request(url, 'GET', data, options)
  49. export const post = (url, data = {}, options = {}) => request(url, 'POST', data, options)
  50. export default request