request.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import service from './newRequest.js'
  2. import store from '../store';
  3. import {
  4. saveUrl,
  5. interceptor
  6. } from '@/utils/loginUtils.js';
  7. // 请求完成后拦截
  8. service.interceptors.response(
  9. response => {
  10. try {
  11. const that = getApp();
  12. let res = response.data;
  13. // 解析字符串为数字
  14. if(res.code == 1 || res.code == 0){
  15. return res
  16. }else{
  17. if(res.code == 401){
  18. // 调用退出登录方法清空用户信息
  19. store.commit('user/logout');
  20. // 判断是否开启强制登录
  21. uni.showModal({
  22. title: that.$t('common.温馨提示'),
  23. content: that.$t('common.您未登录'),
  24. cancelText: that.$t('common.取消'),
  25. confirmText: that.$t('common.确定'),
  26. success: (e) => {
  27. // 判断是否点击确认按钮
  28. if (e.confirm) {
  29. // 保存当前页面地址
  30. saveUrl()
  31. // 跳转页面
  32. interceptor()
  33. }
  34. }
  35. })
  36. }
  37. }
  38. } catch (e) {
  39. console.log(e);
  40. }
  41. },
  42. error => {
  43. const that = getApp();
  44. uni.showToast({
  45. title: that.$t('common.加载错误请重试'),
  46. duration: 1500,
  47. mask: false,
  48. icon: 'none',
  49. })
  50. return Promise.reject(error)
  51. }
  52. )
  53. // 请求前拦截器
  54. service.interceptors.request(
  55. config => {
  56. let token = uni.getStorageSync('tokens') || '';
  57. let lang = ''
  58. if(store.state.lang == 'en'){
  59. lang = 'en-us'
  60. }else{
  61. lang = 'zh-cn'
  62. }
  63. if (!config.header) {
  64. config.header = {
  65. "token":token,
  66. "lang":lang
  67. }
  68. } else {
  69. // 添加key请求头
  70. config.header["token"] = token;
  71. config.header["lang"] = lang
  72. }
  73. return config
  74. },
  75. error => {
  76. // 错误处理
  77. console.log(error)
  78. return Promise.reject(error)
  79. }
  80. )
  81. let upFilse = service.upFilse;
  82. export {
  83. upFilse
  84. };
  85. export default service.open;