vue axios拦截器

axios拦截器

请求拦截器

在请求发出之前设置一些信息

//添加一个请求拦截器
axios.interceptors.request.use(function(config){
  //在请求发出之前进行一些信息设置 
  //必须把configreturn出去否则不生效   return config; },function(err){   //处理响应的错误信息 })

响应拦截器

在获取数据之前对数据做一些加工处理

//添加一个响应拦截器
axios.interceptors.response.use(function(res){
  //在请求发出之前进行一些信息设置 
  return res;
},function(err){
  //处理响应的错误信息
})

在响应拦截器中将所需要的数据提取出来,那么我们在待用接口的时候,就可以直接在then中直接获取我们要的数据,不用再使用res.data调用数据

    axios.interceptors.response.use(function(res) {
      // console.log(res)
      var data = res.data;
      return data;
    }, function(err){
      console.log(err)
    })
    axios.get('http://localhost:3000/adata').then(function(data){
      console.log(data)
    })

 

posted @ 2020-12-22 23:50  黎沐不吃香菜  阅读(241)  评论(0)    收藏  举报