http.interceptor.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { config } from '@/common/config.js';
  2. import store from '../store/index.js'
  3. // 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
  4. // 同时,我们也可以在此使用getApp().globalData,如果你把token放在getApp().globalData的话,也是可以使用的
  5. const install = (Vue, vm) => {
  6. Vue.prototype.$u.http.setConfig({
  7. baseUrl: config.baseUrl,
  8. // 如果将此值设置为true,拦截回调中将会返回服务端返回的所有数据response,而不是response.data
  9. // 设置为true后,就需要在this.$u.http.interceptor.response进行多一次的判断,请打印查看具体值
  10. // originalData: true,
  11. // 设置自定义头部content-type
  12. // header: {
  13. // 'content-type': 'xxx'
  14. // }
  15. });
  16. // 请求拦截,配置Token等参数
  17. Vue.prototype.$u.http.interceptor.request = (config) => {
  18. // config.header.Token = 'xxxxxx';
  19. // 方式一,存放在vuex的token,假设使用了uView封装的vuex方式,见:https://uviewui.com/components/globalVariable.html
  20. // config.header.token = vm.vuex_token;
  21. if(vm.vuex_token){config.header.Authorization = `Bearer ${vm.vuex_token}`;}
  22. // 方式二,如果没有使用uView封装的vuex方法,那么需要使用$store.state获取
  23. // config.header.token = vm.$store.state.token;
  24. // 方式三,如果token放在了globalData,通过getApp().globalData获取
  25. // config.header.token = getApp().globalData.username;
  26. // 方式四,如果token放在了Storage本地存储中,拦截是每次请求都执行的,所以哪怕您重新登录修改了Storage,下一次的请求将会是最新值
  27. // const token = uni.getStorageSync('token');
  28. // config.header.token = token;
  29. // url加时间戳
  30. config.url = config.url + '?t=' + Date.now()
  31. // 此url参数为this.$u.get(url)中的url值
  32. let noTokenList = ['/wechat/h5/user','/client/auth/verifyCode'];
  33. if(noTokenList.includes(config.url)) config.header.noToken = true;
  34. // console.log('noTokenList.includes(config.url)',noTokenList.includes(config.url));
  35. // console.log('config.url',config.url);
  36. return config;
  37. }
  38. // 响应拦截,判断状态码是否通过
  39. Vue.prototype.$u.http.interceptor.response = (res) => {
  40. // 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
  41. // 判断可能变成了res.statueCode,或者res.data.code之类的,请打印查看结果
  42. // console.log('interceptor res',res);
  43. if(res.code == 200) {
  44. // 如果把originalData设置为了true,这里return回什么,this.$u.post的then回调中就会得到什么
  45. return res;
  46. } else if(res.msg == "令牌不能为空" || res.code == 401 || res.code == 400){
  47. const backUrl = location.href
  48. const loginUrl = 'phoneLogin'
  49. if (backUrl.indexOf(loginUrl) > 0) {
  50. localStorage.clear()
  51. } else {
  52. localStorage.setItem('backUrl', location.href)
  53. uni.showToast({
  54. title: res.msg || '!',
  55. duration: 2000,
  56. icon: 'none'
  57. })
  58. uni.navigateTo({
  59. url: "/pages/center/phoneLogin/phoneLogin"
  60. })
  61. }
  62. } else {
  63. uni.showToast({
  64. title: res.msg || '程序错误!',
  65. duration: 2000,
  66. icon: 'none'
  67. })
  68. };
  69. }
  70. }
  71. export default {
  72. install
  73. }