index.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. console.log(config,'config')
  18. // 引用token
  19. let token = uni.getStorageSync('token');
  20. if(config.custom&&config.custom.auth&&!token){
  21. uni.$u.toast('请登录后再操作')
  22. setTimeout(()=>{
  23. vm.$Router.push('/pages/login/login')
  24. },1000)
  25. return new Promise(() => { })
  26. }
  27. if(config.custom&&config.custom.timeout){
  28. config.timeout = config.custom.timeout
  29. }
  30. if(config.method === 'GET'){
  31. config.header = {
  32. 'Content-Type': 'application/json;charset=UTF-8',
  33. }
  34. }else{
  35. config.header = {
  36. 'Content-Type': 'application/json;charset=UTF-8',
  37. }
  38. }
  39. if(config.url.includes('structured-law')){
  40. // config.baseURL = vm.$LAWYER_URL_FG
  41. config.header = {
  42. 'Content-Type': 'application/x-www-form-urlencoded',
  43. }
  44. }
  45. let data = config.method==="GET" ? config.params : config.data;
  46. if(token) {
  47. config.header['x-access-token'] = token
  48. }
  49. return config;
  50. }, config => { // 可使用async await 做异步操作
  51. return Promise.reject(config)
  52. })
  53. // 响应拦截,如配置,每次请求结束都会执行本方法
  54. uni.$u.http.interceptors.response.use(async (response) => {
  55. const data = response.data;
  56. const custom = response.config.custom;
  57. if (data.code <= 0) {
  58. uni.hideLoading()
  59. if (!custom.toast) {
  60. uni.$u.toast(data.msg);
  61. console.log(custom)
  62. }
  63. // 如果需要catch返回,则进行reject
  64. if (custom?.catch) {
  65. return Promise.reject(data)
  66. } else {
  67. // 否则返回一个pending中的promise,请求不会进入catch中
  68. return new Promise(() => { })
  69. }
  70. }
  71. return !data ? {} : data;
  72. },async (response) => {
  73. console.log(response)
  74. uni.hideLoading()
  75. /* 对响应错误做点什么 (statusCode !== 200)*/
  76. if (response.statusCode == 401) {
  77. uni.$u.toast('登录已过期,请重新登录')
  78. store.dispatch('userLogout')
  79. }else if (response.statusCode == 500) {
  80. uni.$u.toast('网络开了点小差,请重试');
  81. } else if (response.statusCode == 404) {
  82. return;
  83. } else {
  84. uni.$u.toast(response.data.msg);
  85. }
  86. return new Promise(() => { });
  87. })
  88. }