图书馆小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

5 months ago
4 months ago
1 month ago
4 months ago
5 months ago
4 months ago
1 month ago
5 months ago
1 month ago
4 months ago
5 months ago
3 weeks ago
5 months ago
4 months ago
5 months ago
3 weeks ago
  1. import store from '../store';
  2. import config from '@/utils/config.js'
  3. const BASE_URL = config.baseUrl
  4. // 把对象转 queryString,数组展开为 key=val&key=val
  5. function buildQuery(params) {
  6. const parts = []
  7. for (const key in params) {
  8. const val = params[key]
  9. if (val === null || val === undefined) continue
  10. if (Array.isArray(val)) {
  11. // 数组:多次追加 key=xxx
  12. val.forEach(item => {
  13. parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(item)}`)
  14. })
  15. } else {
  16. parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
  17. }
  18. }
  19. return parts.join('&')
  20. }
  21. function request({ url, data, method = 'GET' }) {
  22. return new Promise((resolve, reject) => {
  23. // 自动带上 token
  24. const header = {};
  25. if (store.state.user.token) {
  26. header.Authorization = store.state.user.token;
  27. }
  28. let finalUrl = BASE_URL + url
  29. let finalData = data
  30. // GET 请求:手动拼装query,数组展开多同名参数
  31. if (method.toUpperCase() === 'GET' && data && typeof data === 'object') {
  32. const query = buildQuery(data)
  33. if (query) {
  34. finalUrl += (finalUrl.includes('?') ? '&' : '?') + query
  35. }
  36. finalData = undefined // GET 清空data,防止uni.request重复处理
  37. }
  38. uni.request({
  39. url: finalUrl,
  40. data: finalData,
  41. method: method.toUpperCase(),
  42. header,
  43. success: ({ data }) => {
  44. // ✅ 全部直接resolve,业务层自己判断code,不再reject业务错误
  45. resolve(data);
  46. },
  47. fail: (error) => {
  48. uni.showToast({
  49. title: '网络异常',
  50. icon: 'none'
  51. });
  52. reject(error);
  53. },
  54. complete: () => {
  55. uni.hideLoading();
  56. }
  57. });
  58. });
  59. }
  60. export default request;