request.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Taro from '@tarojs/taro';
  2. import ttappid from '../../project.tt.json'; // 抖音
  3. import wxappid from '../../project.config.json'; // 微信
  4. import { baseUrl } from './config';
  5. const getAppId = () => {
  6. if (process.env.TARO_ENV === 'weapp') {
  7. return wxappid.appid;
  8. } else if (process.env.TARO_ENV === 'tt') {
  9. return ttappid.appid;
  10. }
  11. return '';
  12. };
  13. export default async (options = { method: 'GET', data: {} }) => {
  14. const request_data = {
  15. session_key: Taro.getStorageSync('session_key') || '', // 缓存取值
  16. appid: getAppId(),
  17. channel_name: 'WeChat'
  18. };
  19. // 如果是登录接口,移除 session_key
  20. if (options.url.includes('/user/login_applet')) {
  21. delete request_data.session_key;
  22. }
  23. try {
  24. const res = await Taro.request({
  25. url: baseUrl + options.url,
  26. data: {
  27. ...request_data,
  28. ...options.data,
  29. },
  30. header: {
  31. 'Content-Type': 'application/json',
  32. accept: 'application/json',
  33. },
  34. method: options.method.toUpperCase(),
  35. });
  36. const { code,data, msg } = res.data;
  37. console.log('==========',options.url);
  38. console.log('options',options.data);
  39. console.log('res',res);
  40. switch (code) {
  41. case 200:
  42. return data;
  43. case 400:
  44. // Taro.showToast({
  45. // title: '传参有误',
  46. // icon: 'none',
  47. // mask: true,
  48. // });
  49. throw new Error('传参有误');
  50. case 422:
  51. // Taro.showToast({
  52. // title: 'Validation Error',
  53. // icon: 'none',
  54. // mask: true,
  55. // });
  56. throw new Error('Validation Error');
  57. case 500:
  58. Taro.showToast({
  59. title: '需要登录',
  60. icon: 'none',
  61. mask: true,
  62. });
  63. // 获取当前跳转到登录的页面路径
  64. const currentPages = Taro.getCurrentPages();
  65. const currentPage = currentPages[currentPages.length - 1];
  66. if (currentPage) {
  67. // 储存当前页面路径
  68. Taro.setStorageSync('currentPage', currentPage.route);
  69. global.globalData.optionsData = currentPage.options || {};
  70. }
  71. Taro.reLaunch({
  72. url: '/pages/login/index',
  73. });
  74. // throw new Error('需要登录');
  75. return
  76. default:
  77. Taro.showToast({
  78. title: `${msg || '请求失败'}`,
  79. icon: 'none',
  80. mask: true,
  81. });
  82. // throw new Error(msg || '请求失败');
  83. }
  84. } catch (error) {
  85. console.error('请求错误:', error);
  86. return Promise.reject(error);
  87. }
  88. };