request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // 从环境变量中获取基础地址,如果没有设置则使用默认值
  2. const BASE_URL = import.meta.env.VITE_APP_BASE_URL || 'https://default-api-url.com';
  3. // 默认配置
  4. const defaultConfig = {
  5. timeout: 5000, // 默认超时时间为 5000 毫秒
  6. baseURL: BASE_URL // 基础 URL
  7. };
  8. // 辅助函数:将对象转换为查询字符串
  9. function objectToQueryString(obj) {
  10. return Object.keys(obj)
  11. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
  12. .join('&');
  13. }
  14. // 封装请求函数
  15. function request(options) {
  16. const config = {
  17. ...defaultConfig,
  18. ...options
  19. };
  20. // 拼接完整的请求 URL
  21. config.url = config.baseURL + config.url;
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. ...config,
  25. success: (res) => {
  26. resolve(res.data);
  27. },
  28. fail: (err) => {
  29. reject(err);
  30. }
  31. });
  32. });
  33. }
  34. // 封装 GET 请求
  35. export const clientGet = async (url, data = {}) => {
  36. try {
  37. const response = await request({
  38. url,
  39. method: 'GET',
  40. data
  41. });
  42. return response;
  43. } catch (error) {
  44. throw error;
  45. }
  46. };
  47. // 封装 POST 请求
  48. export const clientPost = async (url, data = {}) => {
  49. try {
  50. const response = await request({
  51. url,
  52. method: 'POST',
  53. data
  54. });
  55. return response;
  56. } catch (error) {
  57. throw error;
  58. }
  59. };
  60. // 封装 PUT 请求
  61. export const clientPut = async (url, data = {}) => {
  62. try {
  63. const response = await request({
  64. url,
  65. method: 'PUT',
  66. data
  67. });
  68. return response;
  69. } catch (error) {
  70. throw error;
  71. }
  72. };
  73. // 封装 DELETE 请求
  74. export const clientDelete = async (url, data = {}) => {
  75. try {
  76. const response = await request({
  77. url,
  78. method: 'DELETE',
  79. data
  80. });
  81. return response;
  82. } catch (error) {
  83. throw error;
  84. }
  85. };
  86. // 封装带查询参数的 POST 请求
  87. export const clientPostWithQueryParams = async (url, queryParams = {}, data = {}) => {
  88. try {
  89. const queryString = objectToQueryString(queryParams);
  90. const fullUrl = url + (queryString ? `?${queryString}` : '');
  91. const response = await request({
  92. url: fullUrl,
  93. method: 'POST',
  94. data
  95. });
  96. return response;
  97. } catch (error) {
  98. throw error;
  99. }
  100. };