request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 request(options) {
  10. const config = {
  11. ...defaultConfig,
  12. ...options
  13. };
  14. // 拼接完整的请求 URL
  15. config.url = config.baseURL + config.url;
  16. return new Promise((resolve, reject) => {
  17. uni.request({
  18. ...config,
  19. success: (res) => {
  20. resolve(res.data);
  21. },
  22. fail: (err) => {
  23. reject(err);
  24. }
  25. });
  26. });
  27. }
  28. // 封装 GET 请求
  29. export const clientGet = async (url, data = {}) => {
  30. try {
  31. const response = await request({
  32. url,
  33. method: 'GET',
  34. data
  35. });
  36. return response;
  37. } catch (error) {
  38. throw error;
  39. }
  40. };
  41. // 封装 POST 请求
  42. export const clientPost = async (url, data = {}) => {
  43. try {
  44. const response = await request({
  45. url,
  46. method: 'POST',
  47. data
  48. });
  49. return response;
  50. } catch (error) {
  51. throw error;
  52. }
  53. };
  54. // 封装 PUT 请求
  55. export const clientPut = async (url, data = {}) => {
  56. try {
  57. const response = await request({
  58. url,
  59. method: 'PUT',
  60. data
  61. });
  62. return response;
  63. } catch (error) {
  64. throw error;
  65. }
  66. };
  67. // 封装 DELETE 请求
  68. export const clientDelete = async (url, data = {}) => {
  69. try {
  70. const response = await request({
  71. url,
  72. method: 'DELETE',
  73. data
  74. });
  75. return response;
  76. } catch (error) {
  77. throw error;
  78. }
  79. };