当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的http请求拦截。

1.安装配置axios


cnpm install --save axios

我们可以建一个js文件来做这个统一的处理,新建一个axios.js,如下


import axios from 'axios'
import { Indicator } from 'mint-ui';
import { Toast } from 'mint-ui';
// http request 拦截器
axios.interceptors.request.use(
config => {
Indicator.open()
return config;
},
err => {
Indicator.close()
return Promise.reject(err);
});
// http response 拦截器
axios.interceptors.response.use(
response => {
Indicator.close()
return response;
},
error => {
Indicator.close()
}); //欢迎加入前端全栈开发交流圈一起吹水聊天学习交流:864305860
export default axios

然后在main.js中引入这个js文件


import axios from './axio';
Vue.prototype.$axios = axios;

这样就可以使用axios去请求了,在组件中可以用this.axios去调用


this.$axios({
url:requestUrl+'homePage/v1/indexNewPropertiesResult',
method:'POST',
}).then(function(response){ //接口返回数据
console.log(response)
that.modulesArr=response.data.data.modules;
// that.getRecommendGoods(0);
});//欢迎加入前端全栈开发交流圈一起吹水聊天学习交流:864305860

只有用axios请求接口,才能去拦截,现在已经能在axios.js中拦截到了,可以在两个状态中做你需要的操作

补充:

  • axios使用拦截器统一处理所有的http请求
  • axios使用拦截器
  • 在请求或响应被 then 或 catch 处理前拦截它们。

http request拦截器


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});//欢迎加入前端全栈开发交流圈一起吹水聊天学习交流:864305860

http respones拦截器


// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});//欢迎加入前端全栈开发交流圈一起吹水聊天学习交流:864305860

移除拦截器


var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

为自定义axios实例添加拦截器


var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

结语

感谢您的观看,如有不足之处,欢迎批评指正。

原文地址:https://segmentfault.com/a/1190000017283733

最新文章

  1. iOS--UIAlertView与UIAlertController和UIAlertAction之间的事儿
  2. javascript高级程序设计第四章 变量、作用域和内存问题
  3. javascript 设计模式-----单例模式
  4. Database、User、Schema、Tables、Col、Row
  5. Android-Adapter用法总结
  6. c++中的指针问题
  7. Python网络编程——处理套接字错误
  8. iOS XMPP之常见错误一:(<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>)
  9. oracle日期的处理
  10. JAVA环境变量关于
  11. 北京一家JAVA开发公司面试题(留给后人)
  12. [Swift]LeetCode457. 环形数组循环 | Circular Array Loop
  13. vue用hbuilderX打包app嵌入h5方式云打包和遇到的问题
  14. dskinlite自适应dpi
  15. hive笔记:转义字符的使用
  16. Jenkins二 安装gitlab及其使用
  17. The open source JavaScript graphing library that powers Plotly
  18. Navicat Premium 将sqlserver 数据库 导入mysql 中
  19. Asp连接Oracle (包含绿色版12.2客户端和ODBC驱动安装)
  20. 20155233 2016-2017-2 《Java程序设计》第5周学习总结

热门文章

  1. props 父组件给子组件传递参数
  2. C++入门经典-例5.1-输出变量的指针
  3. 利用Zookeeper实现分布式锁
  4. 使用C#语言,将DataTable 转换成域模型
  5. Java中Redis的简单入门
  6. leetcode-easy-listnode-234 Palindrome Linked List
  7. 深度学习----现今主流GAN原理总结及对比
  8. 监控部署nagios+snmp
  9. "Developer tools access" 需控制另一个进程才能继续调试 解决方案
  10. C#规范整理·语言要素