vue interceptors(拦截器)

发布于:2021-10-15 08:34:02

  拦截器 顾名思义: 就是半路个您劫持

  拦截器 

      其实在项目和自己写demo中,总会遇到请求方面需要在请求头里面做判断或者添加一些东西,

这时候 vue 中应用中axios的 interceptors 其的就能帮助我们做这些事情

 拦截请求

  比如需要在请求头里面加入 token和 签名    加强请求安全性。毕竟请求被攻击太多了 

复制代码

// 拦截请求http.interceptors.request.use(config => {// 请求头添加access_token
  const token = localStorage.getItem('TOKEN') ? JSON.parse(localStorage.getItem('TOKEN')) : ''  if (token && token.access_token ) {
    config.headers['Access-Token'] = token.access_token.value
  }  /*
   * 处理post、put、delete请求
   * 1、data为空时,默认传一个随机参数
   * 2、根据data生成签名
   * 3、转化data为查询参数格式   */
  if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {    // 默认传一个数据
    if (!config.data) {
      config.data = {
        t: new Date().getTime()
      }
    }    // 请求头添加签名
    config.headers.Sign = util.createSign(config.data)    // 转化data数据格式
    config.data = qs.stringify(config.data)
  }  return config
}, error => {
  Toast(error.message)
  Indicator.close()
})

复制代码

拦截响应

 就去请求到数据了,做一些数据判断,比如没有注册之类的,可以跳转到用户注册页面。

  也可以判断请求是的token 是否过期,给它重置。

 

 

复制代码

// 拦截响应http.interceptors.response.use(res => {  // 响应失败
  if (!res.data.success) {
    Toast(res.data.msg)
    Indicator.close()
  }  /**
   * refresh_token过期
   * 1、清空本地token
   * 2、刷新页面   */
  if (res.data.code === '004-1') {
    localStorage.setItem('TOKEN', '')
    window.location.reload()
  }  // 请先绑定手机号
  if (res.data.code === '004-2') {
    router.push({
      name: 'bindMobile'
    })
  }  return res.data
}, error => {
  Toast(error.message)
  Indicator.close()
})

复制代码

 

请求错误

 我一般都会在拦截和响应的 报错的 方法里面:加入自己写的组件比如

  弹出框(错误消息)

 还有就是那种 loading 的停止 动画 这不就完美了

 

       可以结合 es6 中的 promise 来做请求 亦或是 es7 中的 async await,数据 来解决请求 回调地狱,

      当然axios 中提供的 all 请求方式 让2个请求后才执行后面的操作,这样会跟方便,啧啧 ,简直了

 

下面是一些代码片段:

 axios.all([api.getHomeList(), api.getshop()]).then(
        axios.spread(function(acct, perms) {          // 两个请求现在都执行完成
          //console.log(acct,perms)        })
   );

真的感觉前端的变化太大了,快学不动了,还是加油加油吧。

 

https://www.cnblogs.com/yf-html/p/9264865.html


Vue进阶(幺伍伍):vue-resource 拦截器interceptors使用

https://shq5785.blog.csdn.net/article/details/111315184

阅读 112+

一片空白

父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。