index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const baseURL = 'https://api.example.com'; // 替换为您的实际API地址
  2. // 请求拦截器
  3. const requestInterceptor = (config) => {
  4. // 在这里添加token等认证信息
  5. const token = uni.getStorageSync('token');
  6. if (token) {
  7. config.header = {
  8. ...config.header,
  9. 'Authorization': `Bearer ${token}`
  10. };
  11. }
  12. return config;
  13. };
  14. // 响应拦截器
  15. const responseInterceptor = (response) => {
  16. // 在这里处理响应数据
  17. if (response.statusCode === 200) {
  18. return response.data;
  19. }
  20. // 处理错误情况
  21. uni.showToast({
  22. title: response.data.message || '请求失败',
  23. icon: 'none'
  24. });
  25. return Promise.reject(response);
  26. };
  27. // 封装请求方法
  28. const request = (options) => {
  29. const config = requestInterceptor({
  30. ...options,
  31. url: `${baseURL}${options.url}`,
  32. header: {
  33. 'Content-Type': 'application/json',
  34. ...options.header
  35. }
  36. });
  37. return new Promise((resolve, reject) => {
  38. uni.request({
  39. ...config,
  40. success: (res) => {
  41. resolve(responseInterceptor(res));
  42. },
  43. fail: (err) => {
  44. uni.showToast({
  45. title: '网络请求失败',
  46. icon: 'none'
  47. });
  48. reject(err);
  49. }
  50. });
  51. });
  52. };
  53. // 导出请求方法
  54. export default {
  55. get: (url, data = {}, options = {}) => {
  56. return request({
  57. url,
  58. data,
  59. method: 'GET',
  60. ...options
  61. });
  62. },
  63. post: (url, data = {}, options = {}) => {
  64. return request({
  65. url,
  66. data,
  67. method: 'POST',
  68. ...options
  69. });
  70. },
  71. put: (url, data = {}, options = {}) => {
  72. return request({
  73. url,
  74. data,
  75. method: 'PUT',
  76. ...options
  77. });
  78. },
  79. delete: (url, data = {}, options = {}) => {
  80. return request({
  81. url,
  82. data,
  83. method: 'DELETE',
  84. ...options
  85. });
  86. }
  87. };