细说vue axios登录请求拦截器
2024-10-19 13:32:32
当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的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
最新文章
- iOS--UIAlertView与UIAlertController和UIAlertAction之间的事儿
- javascript高级程序设计第四章 变量、作用域和内存问题
- javascript 设计模式-----单例模式
- Database、User、Schema、Tables、Col、Row
- Android-Adapter用法总结
- c++中的指针问题
- Python网络编程——处理套接字错误
- iOS XMPP之常见错误一:(<;failure xmlns=";urn:ietf:params:xml:ns:xmpp-sasl";>;<;not-authorized/>;<;/failure>;)
- oracle日期的处理
- JAVA环境变量关于
- 北京一家JAVA开发公司面试题(留给后人)
- [Swift]LeetCode457. 环形数组循环 | Circular Array Loop
- vue用hbuilderX打包app嵌入h5方式云打包和遇到的问题
- dskinlite自适应dpi
- hive笔记:转义字符的使用
- Jenkins二 安装gitlab及其使用
- The open source JavaScript graphing library that powers Plotly
- Navicat Premium 将sqlserver 数据库 导入mysql 中
- Asp连接Oracle (包含绿色版12.2客户端和ODBC驱动安装)
- 20155233 2016-2017-2 《Java程序设计》第5周学习总结
热门文章
- props 父组件给子组件传递参数
- C++入门经典-例5.1-输出变量的指针
- 利用Zookeeper实现分布式锁
- 使用C#语言,将DataTable 转换成域模型
- Java中Redis的简单入门
- leetcode-easy-listnode-234 Palindrome Linked List
- 深度学习----现今主流GAN原理总结及对比
- 监控部署nagios+snmp
- ";Developer tools access"; 需控制另一个进程才能继续调试 解决方案
- C#规范整理&#183;语言要素