首页 > 其他 > 详细

拦截器

时间:2020-04-07 22:03:13      阅读:54      评论:0      收藏:0      [点我收藏+]

axios拦截器

在src目录下的api目录创建一个js文件

import axios from ‘axios‘  //引入axios
//下面这两个不一定需要引入,看你项目需要拦截的时候做什么操作,但是一般都需要引入store
import store from ‘@/store/index‘  //引入store
import router from ‘@/router‘  //引入router

创建一个axios实例

let instance = axios.create({
  headers: {
    ‘content-type‘: ‘application/x-www-form-urlencoded‘
  }
})

编写请求拦截器

这个拦截器会在你发送请求之前运行
我的这个请求拦截器的功能是为我每一次请求去判断是否有token,如果token存在则在请求头加上这个token。后台会判断我这个token是否过期。

// http request 拦截器
instance.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem(‘token‘)
    if (token ) { // 判断是否存在token,如果存在的话,则每个http header都加上token
      config.headers.authorization = token  //请求头加上token
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

响应拦截器

// http response 拦截器
instance.interceptors.response.use(
  response => {
    //拦截响应,做统一处理 
    if (response.data.code) {
      switch (response.data.code) {
        case 1002:
          store.state.isLogin = false
          router.replace({
            path: ‘login‘,
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
    }
    return response
  },
  //接口错误状态处理,也就是说无响应时的处理
  error => {
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  })

最后把实例导出就行了

export default instance

在需要的页面导入就可以使用了

import instance from ‘./axios‘

/* 验证登陆 */
export function handleLogin (data) {
  return instance.post(‘/ds/user/login‘, data)
}


没有拦截的时候直接全局注册使用
在vue main.js代码如下:
import axios from ‘axios‘
import VueAxios from ‘vue-axios‘
Vue.use(VueAxios, axios)
引用文件中:  
 this.axios.get(‘getLunboImg‘)
    .then((res)=>{
        console.log(res)
        this.bannerList=res.data.detail
    })
    .catch((error)=>{
        console.log(error);
    })
    },
 

拦截器

原文:https://www.cnblogs.com/zwjun/p/12655934.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!