vue+axios 前端实现的常用拦截的代码示例

Axios拦截器配置

main.js

//定义一个请求拦截器 Axios.interceptors.request.use(function(config){ store.state.isShow=true; //在请求发出之前进行一些操作 return config }) //定义一个响应拦截器 Axios.interceptors.response.use(function(config){ store.state.isShow=false;//在这里对返回的数据进行处理 return config })

分别定义一个请求拦截器(请求开始时执行某些操作)、响应拦截器(接受到数据后执行某些操作),之间分别设置拦截时执行的操作,改变state内isShow的布尔值从而控制loading组件在触发请求数据开始时显示loading,返回数据时隐藏loading
特别注意:这里有一个语法坑(我可是来来回回踩了不少次)main.js中调取、操作vuex state中的数据不同于组件中的this.$store.state,而是直接store.state 同上面代码

一、路由拦截使用

router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 判断该路由是否需要登录权限 if (store.state.token) { // 通过vuex state获取当前的token是否存在 next(); } else { next({ path: '/login', query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由 }) } } else { next(); } })

二、拦截器使用

要想统一处理所有http请求和响应,就得用上 axios 的拦截器。通过配置http response inteceptor,当后端接口返回401 Unauthorized(未授权),让用户重新登录。

// http request 拦截器 axios.interceptors.request.use( config => { if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 返回 401 清除token信息并跳转到登录页面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的错误信息 });

三、实例

/** * http配置 */ // 引入axios以及element ui中的loading和message组件 import axios from 'axios' import { Loading, Message } from 'element-ui' // 超时时间 axios.defaults.timeout = 5000 // http请求拦截器 var loadinginstace axios.interceptors.request.use(config => { // element ui Loading方法 loadinginstace = Loading.service({ fullscreen: true }) return config }, error => { loadinginstace.close() Message.error({ message: '加载超时' }) return Promise.reject(error) }) // http响应拦截器 axios.interceptors.response.use(data => {// 响应成功关闭loading loadinginstace.close() return data }, error => { loadinginstace.close() Message.error({ message: '加载失败' }) return Promise.reject(error) }) export default axios

如果你是使用了vux,那么在main.js这样使用:

Vue.prototype.$http.interceptors.response.use()

参考地址:vue中axios解决跨域问题和拦截器使用

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/644ba46659a9c110a5db846f9eca95eb.html