request.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /**
  2. * 网络请求工具类
  3. * 封装uni-app的request方法
  4. */
  5. import errorHandler from './errorHandler.js';
  6. // 基础URL,可以根据环境变量等动态设置
  7. const BASE_URL = 'https://minlong.raycos.com.cn';
  8. // 请求超时时间
  9. const TIMEOUT = 60000;
  10. // 请求拦截器
  11. const requestInterceptor = (config) => {
  12. // 获取token
  13. const token = uni.getStorageSync('token');
  14. // 获取 CSRF token
  15. const csrfToken = uni.getStorageSync('csrfToken');
  16. // 设置请求头
  17. if (!config.header) {
  18. config.header = {};
  19. }
  20. // 添加token到请求头
  21. if (token) {
  22. config.header['Authorization'] = `Bearer ${token}`;
  23. }
  24. // 添加 CSRF token 到请求头
  25. if (csrfToken) {
  26. config.header['X-CSRF-Token'] = csrfToken;
  27. }
  28. // 添加内容类型
  29. if (!config.header['Content-Type']) {
  30. config.header['Content-Type'] = 'application/json';
  31. }
  32. // 添加基础URL
  33. if (!config.url.startsWith('http')) {
  34. config.url = BASE_URL + config.url;
  35. }
  36. // 如果是 POST 请求,也可以添加到请求体
  37. if (config.method === 'POST' && config.data) {
  38. config.data._csrf = csrfToken;
  39. }
  40. return config;
  41. };
  42. // 错误提示
  43. const showError = (message, duration = 2000) => {
  44. // 避免重复显示相同的错误提示
  45. if (showError.lastMessage === message && Date.now() - showError.lastTime < 3000) {
  46. return;
  47. }
  48. uni.showToast({
  49. title: message,
  50. icon: 'none',
  51. duration: duration
  52. });
  53. // 记录最后显示的错误信息和时间
  54. showError.lastMessage = message;
  55. showError.lastTime = Date.now();
  56. };
  57. // 初始化错误提示状态
  58. showError.lastMessage = '';
  59. showError.lastTime = 0;
  60. // 错误码映射表
  61. const ERROR_CODE_MAP = {
  62. 400: '请求参数错误',
  63. 401: '登录已过期,请重新登录',
  64. 403: '没有权限执行此操作',
  65. 404: '请求的资源不存在',
  66. 500: '服务器错误,请稍后重试',
  67. 502: '网关错误',
  68. 503: '服务不可用,请稍后重试',
  69. 504: '网关超时'
  70. };
  71. // 响应拦截器
  72. const responseInterceptor = (response) => {
  73. // 这里可以对响应数据做统一处理
  74. if (response.statusCode === 200) {
  75. // 服务器正常响应
  76. const { data } = response;
  77. // 检查是否有特定错误码
  78. if (data.status === 999 || data.code === 999) {
  79. // 微信 code 无效错误
  80. const error = new Error(data.message || '微信登录失败: code无效');
  81. error.status = 999;
  82. return Promise.reject(error);
  83. }
  84. // 处理成功响应 - 适配不同的返回格式
  85. if (data.status === 2000 || data.code === 0 || data.code === 2000) {
  86. // 如果返回的是完整数据对象,直接返回
  87. if (data.data) {
  88. return data.data;
  89. }
  90. // 如果没有data字段,但有其他用户信息字段,返回整个对象
  91. if (data.openid || data.userId || data.user_id) {
  92. return data;
  93. }
  94. // 默认返回
  95. return data;
  96. } else {
  97. // 业务错误
  98. const error = errorHandler.handleBusinessError(data);
  99. return Promise.reject(error);
  100. }
  101. } else {
  102. // HTTP错误
  103. const error = errorHandler.handleHttpError(response.statusCode, response);
  104. return Promise.reject(error);
  105. }
  106. };
  107. // 请求方法
  108. const request = (options = {}) => {
  109. return new Promise((resolve, reject) => {
  110. // 应用请求拦截器
  111. options = requestInterceptor(options);
  112. // 设置超时时间
  113. if (!options.timeout) {
  114. options.timeout = TIMEOUT;
  115. }
  116. // 发起请求
  117. uni.request({
  118. ...options,
  119. success: (res) => {
  120. try {
  121. // 应用响应拦截器
  122. const data = responseInterceptor(res);
  123. resolve(data);
  124. } catch (error) {
  125. errorHandler.logError(error, 'request.responseInterceptor');
  126. reject(error);
  127. }
  128. },
  129. fail: (err) => {
  130. const error = errorHandler.handleRequestFail(err);
  131. errorHandler.logError(error, 'request.fail');
  132. reject(error);
  133. }
  134. });
  135. });
  136. };
  137. // 封装常用请求方法
  138. const http = {
  139. get(url, data = {}, options = {}) {
  140. return request({
  141. url,
  142. data,
  143. method: 'GET',
  144. ...options
  145. });
  146. },
  147. post(url, data = {}, options = {}) {
  148. return request({
  149. url,
  150. data,
  151. method: 'POST',
  152. ...options
  153. });
  154. },
  155. put(url, data = {}, options = {}) {
  156. return request({
  157. url,
  158. data,
  159. method: 'PUT',
  160. ...options
  161. });
  162. },
  163. delete(url, data = {}, options = {}) {
  164. return request({
  165. url,
  166. data,
  167. method: 'DELETE',
  168. ...options
  169. });
  170. },
  171. // 上传文件
  172. upload(url, filePath, name = 'file', formData = {}, options = {}) {
  173. return new Promise((resolve, reject) => {
  174. // 获取token
  175. const token = uni.getStorageSync('token');
  176. // 设置请求头
  177. const header = options.header || {};
  178. if (token) {
  179. header['Authorization'] = `Bearer ${token}`;
  180. }
  181. // 添加基础URL
  182. if (!url.startsWith('http')) {
  183. url = BASE_URL + url;
  184. }
  185. uni.uploadFile({
  186. url,
  187. filePath,
  188. name,
  189. formData,
  190. header,
  191. success: (res) => {
  192. try {
  193. // 上传接口可能返回的是字符串
  194. if (typeof res.data === 'string') {
  195. res.data = JSON.parse(res.data);
  196. }
  197. // 应用响应拦截器
  198. const data = responseInterceptor({
  199. statusCode: res.statusCode,
  200. data: res.data
  201. });
  202. resolve(data);
  203. } catch (error) {
  204. reject(error);
  205. }
  206. },
  207. fail: (err) => {
  208. showError('文件上传失败');
  209. reject(err);
  210. }
  211. });
  212. });
  213. }
  214. };
  215. export default http;