axios.interceptors.request 支持config自定义参数

在使用axios的请求拦截器axios.interceptors.request对请求数据做处理时,有一个需求就是通过自定义参数needLogin判断该请求是否需要验证登录信息。需要的话,在请求之前,前端就进行一次校验,避免前端存储的登录token已失效情况下任然发送请求增加后台负担。


通过【请求拦截器 】axios.interceptors.request.user((config)=>{}) 进行拦截判断是否 needLogin

main.js设置拦截器

//main.js
import Vue from 'vue';
import router from './router';
import store from './store';
import axios from 'axios';
import vueAxios from 'vue-axios';

Vue.use(vueAxios, axios);
axios.defaults.timeout = 5000;// 请求超时
axios.defaults.baseURL = process.env.VUE_APP_URL;
// axios.defaults.headers.post['Content-Type'] = 'application/json';

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  //1、判断是否需要登录
  console.log(`请求【${config.url}】${config.needLogin?'需要':'不需要'}登录`);
  if(config.needLogin){
    if(store.state.token){
      console.log(`【store.state.token】存在 = ${store.state.token}`);
    }else{
      console.warn(`【store.state.token】不存在`);
      //需要从 localStorage 中重新获取token,获取失败则跳转登录页
    }
  }
  //2、将token添加入头部
  if (store.state.token) {
    //如果vuex中存储有用户token,就把token传给后端
    config.headers.token = `${store.state.token}`;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

let app = new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

然后我们调用axios.request()验证一下

//list.vue
<script>
  export default {
    name: 'list',
    data(){
      return {
        list:[],//列表
      }
    },
    created(){
      console.log('created');
      this.getList();
    },
    methods:{
      getList(){
        this.axios.request({
          needLogin:true,//这里设置了needLogin
          method:"get",
          url:"/test-json/order_list.json",
        }).then((response)=>{
          // console.log('response',response,arguments);
        }).catch((error)=>{
          console.log('error',error,arguments);
        })
      }
    },
  };
</script>

然后,我们会发现


找不到.png

为什么config中找不到needLogin?

因为axios对传入的参数做了过滤处理,我们需要在过滤白名单数组中增加我们需要的字段:

新增needlogin.png

最后重新编译(重启服务)再试一下:


最后.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 夜莺2517阅读 127,811评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 11,847评论 1 6
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 12,737评论 28 53
  • 兔子虽然是枚小硕 但学校的硕士四人寝不够 就被分到了博士楼里 两人一间 在学校的最西边 靠山 兔子的室友身体不好 ...
    待业的兔子阅读 7,515评论 2 9

友情链接更多精彩内容