index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import store from '@/common/store/index.js'
  2. module.exports = (vm) => {
  3. // 环境判断
  4. uni.$u.http.setConfig((config) => {
  5. /* config 为默认全局配置*/
  6. config.header = {
  7. 'Content-Type': 'application/x-www-form-urlencoded',
  8. 'Access-Control-Allow-Headers': '*'
  9. }
  10. config.baseURL = vm.$BASE_URL; /* 根域名 */
  11. // config.baseURL = vm.$LAWYER_URL; /* 根域名 */
  12. config.withCredentials = true;
  13. return config
  14. })
  15. // 请求拦截部分,如配置,每次请求前都会执行
  16. uni.$u.http.interceptors.request.use(async (config) => {
  17. // 引用token
  18. let token = uni.getStorageSync('token');
  19. if(config.custom&&config.custom.auth&&!token){
  20. uni.$u.toast('请登录后再操作')
  21. setTimeout(()=>{
  22. // vm.$Router.push('/pages/account/login/login')
  23. },1000)
  24. return new Promise(() => { })
  25. }
  26. if(config.custom&&config.custom.timeout){
  27. config.timeout = config.custom.timeout
  28. }
  29. if(config.method === 'GET'){
  30. config.header = {
  31. 'Content-Type': 'application/json;charset=UTF-8',
  32. }
  33. }else{
  34. config.header = {
  35. 'Content-Type': 'application/json;charset=UTF-8',
  36. }
  37. }
  38. if(config.url.includes('structured-law')){
  39. // config.baseURL = vm.$LAWYER_URL_FG
  40. config.header = {
  41. 'Content-Type': 'application/x-www-form-urlencoded',
  42. }
  43. }
  44. let data = config.method==="GET" ? config.params : config.data;
  45. if(token) data.token = token;
  46. return config;
  47. }, config => { // 可使用async await 做异步操作
  48. return Promise.reject(config)
  49. })
  50. // 响应拦截,如配置,每次请求结束都会执行本方法
  51. uni.$u.http.interceptors.response.use(async (response) => {
  52. const data = response.data;
  53. const custom = response.config.custom;
  54. if (data.code <= 0) {
  55. uni.hideLoading()
  56. if (!custom.toast) {
  57. uni.$u.toast(data.msg);
  58. console.log(custom)
  59. }
  60. // 如果需要catch返回,则进行reject
  61. if (custom?.catch) {
  62. return Promise.reject(data)
  63. } else {
  64. // 否则返回一个pending中的promise,请求不会进入catch中
  65. return new Promise(() => { })
  66. }
  67. }
  68. return !data ? {} : data;
  69. },async (response) => {
  70. console.log(response)
  71. uni.hideLoading()
  72. /* 对响应错误做点什么 (statusCode !== 200)*/
  73. if (response.statusCode == 401) {
  74. uni.$u.toast('登录已过期,请重新登录')
  75. store.dispatch('userLogout')
  76. }else if (response.statusCode == 500) {
  77. uni.$u.toast('网络开了点小差,请重试');
  78. } else if (response.statusCode == 404) {
  79. return;
  80. } else {
  81. uni.$u.toast(response.data.msg);
  82. }
  83. return new Promise(() => { });
  84. })
  85. }