Axios 拦截器 请求拦截器 响应拦截器

请求拦截器

相当于一个关卡,如果满足条件就放行请求,不满足就拦截

响应拦截器 在处理结果之前,先对结果进行预处理,比如:对数据进行一下格式化的处理

全局请求拦截器

javascript 复制代码
axios.interceptors.request.use(config => {
//请求之前需要做的一些事情
	
 	//config.url = 'www.xcccc.com'
    //请求请修改请求的url

    //config.timeout = 2000
    //请求前修改超时时间

    //config.method = 'POST'
    //修改请求方式

    return config //请求成功必须返回
}, error => {

    return Promise.reject(error) //请求失败时的函数
 
}

config 参数


全局响应拦截器

javascript 复制代码
axios.interceptors.response.use(response => {


    console.log(response)

    //return response.data
    //直接将 res.data数据返回
	return response
}, error => {

    console.log('响应数据失败')
    return Promise.reject(error)
    //请求失败时的函数
}
)

也可以在请求回来时对数据进行处理,下面是response的对象


拦截器执行顺序

请求拦截器成功=》响应拦截器成功


请求拦截器失败=》响应拦截器失败 =》请求失败的自定义回调(非必须)


请求拦截器成功=》(服务器404) =》 响应拦截器失败 =》请求失败的自定义回调


完整代码

main.js

javascript 复制代码
import '@/api'

api.js

javascript 复制代码
import axios from "axios";
import Vue from "vue";

//请求拦截器 表示请求要发出时需要的操作
axios.interceptors.request.use(config => {

    // config.url = 'www.xcccc.com'
    // //请求请修改请求的url

    // config.timeout = 2000
    // //请求前修改超时时间

    // config.method = 'POST'
    // //修改请求方式


    console.log('请求时发送成功')

    return config //请求成功必须返回
}, error => {

    console.log('请求时发送失败')
    return Promise.reject(error)
    //请求失败时的函数
})

axios.interceptors.response.use(response => {

    return response
    //直接将 res.data数据返回
}, error => {

    console.log('响应数据失败')
    return Promise.reject(error)
}
)

Vue.prototype.$axios = axios
javascript 复制代码
 this.$axios.get('https://apis.jxcxin.cn/api/mi?user=177********&password=******&step=8000',).then(res => 
 {
            console.log(res)
            
}).catch(error => {

            console.log('请求失败自定义的回调')
            
          })
相关推荐
BillKu21 分钟前
Vue3 Element Plus 对话框加载实现
javascript·vue.js·elementui
醍醐三叶23 分钟前
C++类与对象--2 对象的初始化和清理
开发语言·c++
郝YH是人间理想1 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core1 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
初遇你时动了情1 小时前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
Magnum Lehar1 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8572 小时前
java集合
java·开发语言·windows
成功人chen某2 小时前
配置VScodePython环境Python was not found;
开发语言·python
QQ2740287562 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔2 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器