request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { API_BASE_URL, REQUEST_TIMEOUT_MS } from './config.js'
  2. /**
  3. * 解析后端统一响应。成功返回 data;失败抛 Error(message 为业务文案)。
  4. * @param {{ code?: number, message?: string, data?: any }} body
  5. * @param {number} [httpStatus]
  6. */
  7. export function unwrapResponse(body, httpStatus) {
  8. if (body == null || typeof body !== 'object') {
  9. const err = new Error('网络异常,请稍后重试')
  10. err.code = 'BAD_RESPONSE'
  11. throw err
  12. }
  13. const code = body.code
  14. if (code === 200) {
  15. return body.data
  16. }
  17. const msg =
  18. (typeof body.message === 'string' && body.message.trim()) ||
  19. '请求失败'
  20. const err = new Error(msg)
  21. err.code = code
  22. err.httpStatus = httpStatus
  23. throw err
  24. }
  25. function joinUrl(path) {
  26. const base = (API_BASE_URL || '').replace(/\/$/, '')
  27. const p = path.startsWith('/') ? path : `/${path}`
  28. return `${base}${p}`
  29. }
  30. /**
  31. * @param {{ url: string, method?: string, data?: any, header?: Record<string, string> }} options
  32. * @returns {Promise<any>} data 字段
  33. */
  34. export function request(options) {
  35. const method = (options.method || 'GET').toUpperCase()
  36. const url = joinUrl(options.url)
  37. const header = Object.assign(
  38. { 'Content-Type': 'application/json' },
  39. options.header || {}
  40. )
  41. return new Promise((resolve, reject) => {
  42. uni.request({
  43. url,
  44. method,
  45. data: options.data,
  46. header,
  47. timeout: REQUEST_TIMEOUT_MS,
  48. success(res) {
  49. try {
  50. if (res.statusCode >= 200 && res.statusCode < 300) {
  51. resolve(unwrapResponse(res.data, res.statusCode))
  52. return
  53. }
  54. // HTTP 非 2xx:若 body 仍是业务包,优先展示 message
  55. try {
  56. resolve(unwrapResponse(res.data, res.statusCode))
  57. } catch (bizErr) {
  58. reject(bizErr)
  59. }
  60. } catch (e) {
  61. reject(e)
  62. }
  63. },
  64. fail() {
  65. const err = new Error('网络异常,请稍后重试')
  66. err.code = 'NETWORK'
  67. reject(err)
  68. }
  69. })
  70. })
  71. }
  72. export function get(url, header) {
  73. return request({ url, method: 'GET', header })
  74. }
  75. export function post(url, data, header) {
  76. return request({ url, method: 'POST', data, header })
  77. }