vue axios登录请求拦截器

编程学习 2021-07-04 17:33www.dzhlxh.cn编程入门
这篇文章主要介绍了vue axios登录请求拦截器,判断是否登录超时,或对请求结果做一个统一处理的教程详解,需要的朋友可以参考下

当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的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() 
  }); 
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); 
   }); 

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

补充:

axios使用拦截器统一处理所有的http请求

axios使用拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

•http request拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config;
 }, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
 });

•http respones拦截器

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
 }, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
 });

•移除拦截器

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

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板