request.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import config from '@/config.js'; // 引入配置文件
  2. import store from '@/store'
  3. let apiBaseUrl = '';
  4. // console.log(process.env.NODE_ENV)
  5. if (process.env.NODE_ENV === 'development') {//本地开发环境
  6. const SYSTEM_INFO = uni.getSystemInfoSync();//获取系统信息的同步接口
  7. apiBaseUrl = SYSTEM_INFO.uniPlatform === 'web' ? config.proxyBaseUrl:config.apiBaseUrl;//读取配置文件的apiBaseUrl变量
  8. } else {//生产/测试环境
  9. apiBaseUrl = config.apiBaseUrl
  10. }
  11. console.log(process.env.NODE_ENV,apiBaseUrl)
  12. const request = (options) => {
  13. if(options.url.endsWith('.js')) return;
  14. // console.log("进入requset",options);
  15. return new Promise((resolve, reject) => {
  16. // console.log("进入Promise",options);
  17. let contentType = 'application/json';//默认请求头content-type
  18. // 根据请求方法和请求数据类型设置请求头content-type 以下方法在安卓里报错
  19. // if (options.method === 'POST' && options.data instanceof FormData)
  20. // {
  21. // // FormData 请求头content-type
  22. // contentType = 'multipart/form-data';
  23. // } else if (options.method === 'POST' && typeof options.data === 'string')
  24. // {
  25. // // 字符串请求头content-type
  26. // contentType = 'application/x-www-form-urlencoded';
  27. // }
  28. // console.log("准备请求");
  29. uni.request({
  30. url: apiBaseUrl + options.url,
  31. method: options.method || 'GET',
  32. data: options.data || {},
  33. header: {
  34. 'content-type': contentType,
  35. ...(options.header || {})
  36. },
  37. success: (res) => {
  38. if (res.statusCode === 200) {
  39. resolve(res);
  40. } else {
  41. reject(res);
  42. }
  43. },
  44. fail: (err) => {
  45. reject(err);
  46. }
  47. });
  48. });
  49. };
  50. // 请求拦截器
  51. const requestInterceptor = (config) => {
  52. // 在发送请求之前做些什么
  53. const token = uni.getStorageSync('token'); // 假设从本地存储获取token
  54. // 确保 options.header 存在
  55. if (!config.header) {
  56. config.header = {};
  57. }
  58. if (token) {
  59. config.header.Authorization = `${token}`; // 添加token请求头
  60. }
  61. return config;
  62. };
  63. const isLoginPage = () => {
  64. const pages = getCurrentPages();
  65. if (pages.length === 0) return false;
  66. const currentPage = pages[pages.length - 1];
  67. return currentPage.route === 'pages/login/index';
  68. };
  69. const responseInterceptor = (response) => {
  70. if (response.data.code === 401) {
  71. store.dispatch('logout', true);
  72. if (!isLoginPage()) {
  73. uni.redirectTo({
  74. url: '/pages/login/index'
  75. });
  76. }
  77. throw new Error(response.data.message || '未授权,请重新登录');
  78. }
  79. if (response.data.code === 500 || response.data.code === 503) {
  80. uni.showToast({
  81. title: response.data.message || '服务器繁忙,请稍后重试',
  82. icon: 'none',
  83. duration: 3000
  84. });
  85. throw new Error(response.data.message || '服务器内部错误');
  86. }
  87. if (response.data.code === 200 || response.data.code === 400 || response.data.code === 601 || response.data.code === 602) {
  88. return response.data;
  89. }
  90. if (response.data.code === 403) {
  91. throw new Error(response.data.message || '禁止访问');
  92. }
  93. if (response.data.code === 404) {
  94. throw new Error(response.data.message || '资源未找到');
  95. }
  96. throw new Error(`未知错误,状态码: ${response.statusCode}`);
  97. };
  98. const requestWithInterceptors = (options) => {
  99. // console.log("进来了",options);
  100. const config = requestInterceptor(options);
  101. // console.log("进来了",config);
  102. return request(config).then(responseInterceptor);
  103. };
  104. // 封装常用的请求方法
  105. const get = (url, data, header) => {
  106. return requestWithInterceptors({ url, data, header, method: 'GET' });
  107. };
  108. const post = (url, data, header) => {
  109. return requestWithInterceptors({ url, data, header, method: 'POST' });
  110. };
  111. const put = (url, data, header) => {
  112. return requestWithInterceptors({ url, data, header, method: 'PUT' });
  113. };
  114. const del = (url, data, header) => {
  115. return requestWithInterceptors({ url, data, header, method: 'DELETE' });
  116. };
  117. export default {
  118. request,
  119. get,
  120. post,
  121. put,
  122. del
  123. };