当前位置: 首页 > java >正文

axios拦截器

拦截器的基本概念

拦截器分为两种:

  1. 请求拦截器:在请求发送前执行,可用于添加认证头、修改请求参数等。
  2. 响应拦截器:在响应返回后执行,可用于统一处理错误、解析数据等。

核心方法

1. axios.interceptors.request.use(fulfilled, rejected)
  • 作用:添加请求拦截器。
  • 参数
    • fulfilled:成功回调,接收 config 对象(包含请求配置),需返回修改后的 config
    • rejected:失败回调,接收错误对象,需返回 Promise.reject(error)
axios.interceptors.request.use((config) => {// 添加认证头config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;return config;},(error) => {console.error('请求错误:', error);return Promise.reject(error);}
);
2. axios.interceptors.response.use(fulfilled, rejected)
  • 作用:添加响应拦截器。
  • 参数
    • fulfilled:成功回调,接收 response 对象,可返回处理后的数据。
    • rejected:失败回调,接收错误对象,可处理 HTTP 错误(如 401、500)。
axios.interceptors.response.use((response) => {// 只返回响应数据return response.data;},(error) => {if (error.response) {// 处理 HTTP 错误console.error(`HTTP 错误 ${error.response.status}`);}return Promise.reject(error);}
);
3. axios.interceptors.request.eject(id)axios.interceptors.response.eject(id)
  • 作用:移除拦截器。
  • 参数
    • id:拦截器的唯一标识,由 use() 方法返回。
// 保存拦截器 ID
const requestInterceptor = axios.interceptors.request.use((config) => {// ...return config;
});// 移除拦截器
axios.interceptors.request.eject(requestInterceptor);

拦截器执行顺序

  • 请求拦截器:后添加的先执行(类似栈结构)。
  • 响应拦截器:先添加的先执行(类似队列结构)。
// 请求拦截器顺序:2 → 1
axios.interceptors.request.use((config) => { console.log('拦截器1'); return config; });
axios.interceptors.request.use((config) => { console.log('拦截器2'); return config; });// 响应拦截器顺序:1 → 2
axios.interceptors.response.use((response) => { console.log('拦截器1'); return response; });
axios.interceptors.response.use((response) => { console.log('拦截器2'); return response; });

常见应用场景

  1. 统一添加认证信息

    axios.interceptors.request.use((config) => {config.headers.Authorization = `Bearer ${token}`;return config;
    });
    
  2. 错误处理

    axios.interceptors.response.use((response) => response,(error) => {if (error.response.status === 401) {// 处理未授权错误(如跳转到登录页)}return Promise.reject(error);}
    );
    
  3. 请求/响应日志记录

    axios.interceptors.request.use((config) => {console.log(`请求: ${config.method} ${config.url}`);return config;
    });
    
  4. 超时处理

    axios.interceptors.request.use((config) => {config.timeout = 5000; // 5秒超时return config;
    });
    

注意事项

  1. 必须返回值

    • fulfilled 回调中必须返回 configresponse,否则请求/响应会被中断。
    • rejected 回调中必须返回 Promise.reject(error)
  2. 异步操作

    • 拦截器中可以进行异步操作(如刷新 token),但需返回 Promise
  3. 全局 vs 实例拦截器

    • 全局拦截器(axios.interceptors)会影响所有请求。
    • 实例拦截器(axios.create().interceptors)仅影响特定实例。

总结

Axios 拦截器通过 use() 添加,通过 eject() 移除,是处理请求和响应的强大工具。合理使用拦截器可以大幅提高代码的可维护性和复用性。

http://www.xdnf.cn/news/15256.html

相关文章:

  • Java 大视界 -- Java 大数据在智能安防视频监控系统中的视频摘要快速生成与检索优化(345)
  • Oracle SQL - 使用行转列PIVOT减少表重复扫描(实例)
  • 前端-CSS-day3
  • 【FreeRTOS】事件组
  • 决策树学习
  • OneCode3.0 VFS分布式文件管理API速查手册
  • 网络安全的基本练习
  • Autosar CanSM配置-Busoff参数-基于ETAS软件
  • 齿轮主要的几项精度指标及检测项目学习
  • houdini vat 学习笔记
  • 日志不再孤立!用 Jaeger + TraceId 实现链路级定位
  • 力扣刷题(第八十五天)
  • 【CMake】CMake构建项目入门
  • 【华为OD】MVP争夺战(C++、Java、Python)
  • 多表查询-4-外连接
  • 使用包管理工具CocoaPods、SPM、Carthage的利弊与趋势
  • 【机器学习入门巨详细】(研0版)二创OPEN MLSYS
  • CTFHub————Web{信息泄露[Git泄露(Stash、Index)]}
  • Linux进程管理的核心:task_struct中的双链表与网状数据结构
  • 数据结构之并查集和LRUCache
  • Waiting for server response 和 Content Download
  • Pandas 模块之数据的读取
  • 骁龙8 Gen4前瞻:台积3nm工艺如何平衡性能与发热
  • 【leetcode】709. 转换成小写字母
  • 赋能家庭、行业与工业场景,智微智能新一代Twin Lake 全栈智能终端发布
  • 用一张“冰裂纹”石墨烯薄膜,让被动散热也能做 AI 推理——基于亚波长裂纹等离激元的零功耗温度-逻辑门
  • 基于YOLO11的垃圾分类AI模型训练实战
  • MCP上的数据安全策略:IAM权限管理与数据加密实战
  • wedo智能车库-----第31节(免费分享图纸)
  • 独立开发第二周:构建、执行、规划