index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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/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) {
  46. config.header['x-access-token'] = token
  47. }
  48. return config;
  49. }, config => { // 可使用async await 做异步操作
  50. return Promise.reject(config)
  51. })
  52. // 响应拦截,如配置,每次请求结束都会执行本方法
  53. uni.$u.http.interceptors.response.use(async (response) => {
  54. const data = response.data;
  55. const custom = response.config.custom;
  56. if (data.code <= 0) {
  57. uni.hideLoading()
  58. if (!custom.toast) {
  59. uni.$u.toast(data.msg);
  60. console.log(custom)
  61. }
  62. // 如果需要catch返回,则进行reject
  63. if (custom?.catch) {
  64. return Promise.reject(data)
  65. } else {
  66. // 否则返回一个pending中的promise,请求不会进入catch中
  67. return new Promise(() => { })
  68. }
  69. }
  70. return !data ? {} : data;
  71. },async (response) => {
  72. console.log(response)
  73. uni.hideLoading()
  74. /* 对响应错误做点什么 (statusCode !== 200)*/
  75. if (response.statusCode == 401) {
  76. uni.$u.toast('登录已过期,请重新登录')
  77. store.dispatch('userLogout')
  78. }else if (response.statusCode == 500) {
  79. uni.$u.toast('网络开了点小差,请重试');
  80. } else if (response.statusCode == 404) {
  81. return;
  82. } else {
  83. uni.$u.toast(response.data.msg);
  84. }
  85. return new Promise(() => { });
  86. })
  87. }