Vue添加请求拦截器

一、现象

统一处理错误及配置请求信息

二、解决

1、安装 axios  , 命令: npm install axios --save-dev

2、在根目录的config目录下新建文件 axios.js  ,内容如下:

import axios from ‘axios‘

// 配置默认的host,假如你的API host是:http://api.htmlx.club
axios.defaults.baseURL = ‘http://api.htmlx.club‘

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

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

3、在main.js中进行引用,并配置一个别名($ajax)来进行调用:

import axios from ‘axios‘
import ‘../config/axios‘

Vue.prototype.$ajax = axios

如图:

4、应用,一个登录的post如:

this.$ajax({
  method: ‘post‘,
  url: ‘/login‘,
  data: {
    ‘userName‘: ‘xxx‘,
    ‘password‘: ‘xxx‘
  }
}).then(res => {
  console.log(res)
})

三、总结

统一处理方便

例:

使用iview框架,在main.js添加请求接口拦截器 loading

axios.interceptors.request.use(function (config) {
  iView.LoadingBar.start()
  return config
}),function (error) {
  iView.LoadingBar.error()
  return Promise.reject(error)
}
axios.interceptors.response.use(function (config) {
  iView.LoadingBar.finish()
  return config
}),function (error) {
  iView.LoadingBar.error()
  return Promise.reject(error)
}

/**
 * @export
 * @param {any} request
 * @param {any} next
 * @returns
   */
import store from ‘./vuex/store‘
// 全局错误处理,全局loading
import { setLoading, setTip } from ‘./vuex/actions/doc_actions‘
export default function (request, next) {
  if (request.tip !== false) {
    setLoading(store, true)
  }
  next((res) => {
    setLoading(store, false)
    let data = JSON.parse(res.data)
    if (res.status === 0) {
      setTip(store, {
        text: ‘网络不给力,请稍后再试‘
      })
    }
    if (!data.success) {
      setTip(store, {
        text: data.error_msg
      })
    }
  })
}

原文地址:https://www.cnblogs.com/sweet-ice/p/10520375.html

时间: 2024-08-30 02:19:17

Vue添加请求拦截器的相关文章

vue配置请求拦截器和响应拦截器

首先确保我们已经设置的store.js进行值的存取,这时候我们需要配置请求和响应的拦截器设置 main.js import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import axios from 'axios' // 引入store i

细说vue axios登录请求拦截器

当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的http请求拦截. 1.安装配置axios cnpm install --save axios 我们可以建一个js文件来做这个统一的处理,新建一个axios.js,如下 import axios from 'axios' import { Indicator } from 'mint-ui'; import { Toast } from 'min

Vue+Axios:使用拦截器来取消多次重复的请求

-----写在前面----- 家园的面试项目接近尾声了,剩下一个大模块(响应式布局)和两个小功能(下拉到一定程度获取新的信息.持续监听返回数据,当有更新时在页面上方提示) 听起来下拉到某个位置获取新信息是不难,但今天就遇到了两个问题: 1. 下拉过程中会不断发起url相同的请求,可能会有被拉黑的风险,并且影响实际性能.最重要的,在then()方法中会将返回数据稍做处理后添加进组件数据,并且会驱动Vue更新DOM, 因为用的v-for来填充数据,这样同一条数据就会被渲染两次 2.ReadHub除了

vue 路由拦截器和请求拦截器

vue 拦截器 路由拦截器 已路由为导向 router.beforeEach((to,from,next)=>{ if(to.path=='/login' || localStorage.getItem('token')){ next(); }else{ alert('请重新登录'); next('/login'); } }) 请求拦截器 当发送请求时才会触发此功能 axios.interceptors.request.use(function (config) { let token = wi

Vue进行请求拦截

/** * http响应拦截器 */ import  axios  from  'axios' import  {  Toast, Indicator  }  from  'mint-ui' //Toast提示 import router from '../router' //路由 ///request拦截器 axios.interceptors.request.use(req  =>  {  //向请求头添加token let token = localStorage.getItem('tok

[原创]java WEB学习笔记64:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) ModelDriven拦截器 paramter 拦截器

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

mybatis Spring MVC添加分页拦截器

网上有很多封装的mybatis 分页拦截器,但是看起来都比较乱,不能直接套用,在这里贴出项目中的分页源码出来供大家参考. Controller 层: @RequestMapping("/channelList") public String channelList(HttpServletRequest request,AppMarket appMarket,Model model){ String pageNo = request.getParameter("pageNo&q

vue下axios拦截器token刷新机制

//创建http.js文件,以下是具体代码: //引入安装的axios插件 import axios from 'axios' import router from '@/router'; import Vue from 'vue' const qs = require("qs"); let _this = new Vue(); let isLock = false; let refreshSubscribers = []; //判断token是否过期 function isToken

请求--拦截器--action经过

引用我这里想知道的是同名的多个参数,会被自动的放置在List或者数组中,我想知道是怎么实现的,因为取一个参数和取多个同名的参数是不同的方法: 一个是request.getParameter 一个是request.getParameterValues 先解释一下: Struts或则XWorlk提供的Interceptor,操作的是已经被封装好的Parameters的Map了.相信你应该看到过这句话.(在CheckboxInterceptor中有) Java代码 收藏代码Map parameters