request.js 1000 B

123456789101112131415161718192021222324252627282930313233
  1. const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
  2. const request = (options) => {
  3. return new Promise((resolve, reject) => {
  4. const token = uni.getStorageSync('token')
  5. uni.request({
  6. url: BASE_URL + options.url,
  7. method: options.method || 'GET',
  8. data: options.data || {},
  9. header: {
  10. 'Content-Type': 'application/json',
  11. ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
  12. ...options.header,
  13. },
  14. success: (res) => {
  15. if (res.statusCode === 200) {
  16. resolve(res.data)
  17. } else if (res.statusCode === 401) {
  18. uni.removeStorageSync('token')
  19. uni.reLaunch({ url: '/pages/login/index' })
  20. reject(new Error('未授权,请重新登录'))
  21. } else {
  22. reject(new Error(res.data?.msg || '请求失败'))
  23. }
  24. },
  25. fail: (err) => {
  26. reject(new Error(err.errMsg || '网络错误'))
  27. },
  28. })
  29. })
  30. }
  31. export default request