request.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // const BASE_URL = 'http://127.0.0.1:8080';
  2. // const BASE_URL = 'http://192.168.1.205:8080';
  3. const BASE_URL = 'https://app.jxhsal.com/api';
  4. const CLIENT_ID = 'e48ac397bff4f031b14d6e671eee49c3';
  5. let isRedirectingToLogin = false;
  6. function getToken() {
  7. return uni.getStorageSync('token') || '';
  8. }
  9. function redirectToLogin() {
  10. if (isRedirectingToLogin) return;
  11. isRedirectingToLogin = true;
  12. uni.showToast({ title: '登录已失效,请重新登录', icon: 'none', duration: 1500 });
  13. setTimeout(() => {
  14. isRedirectingToLogin = false;
  15. uni.reLaunch({ url: '/pages/login/index' });
  16. }, 1500);
  17. }
  18. function request(options = {}) {
  19. const { url, method = 'GET', data = {}, params = {}, header = {} } = options;
  20. const token = getToken();
  21. const headers = {
  22. 'Content-Type': 'application/json',
  23. 'clientid': CLIENT_ID,
  24. 'Authorization': 'Bearer ' + token,
  25. ...header
  26. };
  27. let requestData = data;
  28. let requestUrl = BASE_URL + url;
  29. if (method.toUpperCase() === 'GET') {
  30. const allParams = { ...params, ...data };
  31. const paramString = Object.keys(allParams)
  32. .filter(key => allParams[key] !== undefined && allParams[key] !== null && allParams[key] !== '')
  33. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(allParams[key])}`)
  34. .join('&');
  35. if (paramString) {
  36. requestUrl += (requestUrl.includes('?') ? '&' : '?') + paramString;
  37. }
  38. requestData = {};
  39. }
  40. return new Promise((resolve, reject) => {
  41. uni.request({
  42. url: requestUrl,
  43. method,
  44. data: requestData,
  45. header: headers,
  46. success(res) {
  47. const { code, msg, data, total, rows } = res.data;
  48. if (code === 200) {
  49. const result = {};
  50. if (data !== undefined) result.data = data;
  51. if (total !== undefined) result.total = total;
  52. if (rows !== undefined) result.rows = rows;
  53. resolve(result);
  54. } else if (code === 401) {
  55. redirectToLogin();
  56. reject('登录已失效');
  57. } else if (code === 500) {
  58. reject(msg);
  59. } else {
  60. reject(msg || '请求失败');
  61. }
  62. },
  63. fail(err) {
  64. const message = err.errMsg || '网络请求失败';
  65. uni.showToast({ title: message, icon: 'none' });
  66. reject(message);
  67. }
  68. });
  69. });
  70. }
  71. export default request;