云链智安app
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

request.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // 基础配置
  2. const BASE_URL = process.env.VUE_APP_BASE_URL || 'https://esos-iot.bjdexn.cn'; // 从环境变量中获取 BASE_URL
  3. const TIMEOUT = 100000; // 请求超时时间
  4. // 请求拦截器
  5. const requestInterceptor = (config) => {
  6. // 在请求发送前处理
  7. config = {
  8. ...config,
  9. withCredentials: true,
  10. }
  11. // console.log('请求拦截器:', config);
  12. return config;
  13. };
  14. // 响应拦截器
  15. const responseInterceptor = (response) => {
  16. // 在响应返回后处理
  17. // console.log('响应拦截器:', response);
  18. // 处理响应数据statusCode
  19. if (response.statusCode === 200) {
  20. return response.data;
  21. } else {
  22. return Promise.reject(response.data);
  23. }
  24. };
  25. // 错误处理
  26. const errorHandler = (error) => {
  27. uni.reLaunch({
  28. url:'/pages/login/index'
  29. })
  30. console.error('请求失败:', error);
  31. // document.cookie = "rememberMe=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/user/;";
  32. // 统一处理错误
  33. if (error.errMsg) {
  34. uni.showToast({
  35. title: error.errMsg,
  36. icon: 'none',
  37. });
  38. }
  39. return Promise.reject(error);
  40. };
  41. // 封装请求方法
  42. const request = (options) => {
  43. // 合并配置
  44. // console.log(BASE_URL);
  45. // console.log(`${BASE_URL}${options.url}`);
  46. const config = {
  47. url: `${BASE_URL}${options.url}`,
  48. method: options.method || 'GET',
  49. header: options.header|| {},
  50. data: options.data || {},
  51. timeout: TIMEOUT,
  52. withCredentials: true
  53. // ...options,
  54. };
  55. // console.log(config);
  56. // 请求拦截器
  57. const finalConfig = requestInterceptor(config);
  58. // 返回 Promise
  59. return new Promise((resolve, reject) => {
  60. uni.request({
  61. ...finalConfig,
  62. success: (response) => {
  63. // 响应拦截器
  64. const data = responseInterceptor(response);
  65. // console.log(data);
  66. resolve(data);
  67. },
  68. fail: (error) => {
  69. // 错误处理
  70. errorHandler(error);
  71. reject(error);
  72. },
  73. });
  74. });
  75. };
  76. // 导出请求方法
  77. export default request;