Axios配置中的请求响应拦截器

在 Axios 中,你可以配置请求拦截器(Request Interceptors)和响应拦截器(Response Interceptors)来处理在请求发送到服务器之前和服务器响应返回客户端之后的逻辑。

请求拦截器

请求拦截器可以在请求被发送到服务器之前对其进行修改。例如,你可能想在所有请求中添加认证令牌(token)、设置请求头、或者对请求数据进行某种转换。

以下是如何在 Axios 中设置请求拦截器的示例:

|---|------------------------------------------------------------------------------|
| | axios.interceptors.request.use(function (config) { |
| | // 在发送请求之前做些什么 |
| | // 例如,添加请求头或转换数据 |
| | // 可以在这里设置全局的token |
| | if (localStorage.getItem('token')) { |
| | config.headers.Authorization = 'Bearer ' + localStorage.getItem('token'); |
| | } |
| | return config; |
| | }, function (error) { |
| | // 对请求错误做些什么 |
| | return Promise.reject(error); |
| | }); |

响应拦截器

响应拦截器可以在服务器响应返回客户端之后对其进行处理。例如,你可能想检查响应状态码,如果状态码表示错误,你可能想进行某种错误处理或重试逻辑。或者,你可能想对响应数据进行某种转换。

以下是如何在 Axios 中设置响应拦截器的示例:

|---|-----------------------------------------------------------|
| | axios.interceptors.response.use(function (response) { |
| | // 对响应数据做点什么 |
| | // 例如,检查响应状态码,如果状态码表示错误,进行错误处理 |
| | if (response.status >= 200 && response.status < 300) { |
| | // 如果响应成功,返回数据 |
| | return response.data; |
| | } else { |
| | // 如果响应失败,抛出错误 |
| | return Promise.reject(response); |
| | } |
| | }, function (error) { |
| | // 对响应错误做点什么 |
| | if (error.response) { |
| | // 请求已发出,但服务器响应的状态码不在 2xx 范围内 |
| | console.log(error.response.data); |
| | console.log(error.response.status); |
| | console.log(error.response.headers); |
| | } else if (error.request) { |
| | // 请求已发出,但没有收到响应 |
| | // 例如,请求超时或请求被取消 |
| | console.log(error.request); |
| | } else { |
| | // 发送请求时发生了一些事情,导致请求没有发出 |
| | console.log('Error', error.message); |
| | } |
| | return Promise.reject(error); |
| | }); |

移除拦截器

在某些情况下,你可能需要移除之前添加的拦截器。你可以通过返回拦截器函数时的引用来做到这一点。例如:

|---|------------------------------------------------------------------------------------|
| | const myRequestInterceptor = axios.interceptors.request.use(function (config) { |
| | // ... |
| | }); |
| | |
| | // 稍后,当你想移除这个拦截器时: |
| | axios.interceptors.request.eject(myRequestInterceptor); |

注意:eject 方法在 Axios 的较新版本中已被 remove 方法取代。所以你应该使用 remove 而不是 eject

假设我们正在开发一个需要身份验证的 Web 应用,我们将使用 Axios 发起 HTTP 请求,并使用拦截器来处理身份验证和响应数据。

安装 Axios

首先,确保你已经安装了 Axios。如果还没有安装,可以通过 npm 或 yarn 进行安装:

|---|----------------------|
| | npm install axios |
| | # 或者 |
| | yarn add axios |

配置 Axios 拦截器

在项目的某个文件中(比如 api.jsaxiosConfig.js),我们可以配置 Axios 的拦截器:

|---|-----------------------------------------------------------|
| | import axios from 'axios'; |
| | |
| | // 创建 Axios 实例 |
| | const instance = axios.create({ |
| | baseURL: 'https://api.example.com', // 你的 API 基础 URL |
| | timeout: 5000, // 请求超时时间 |
| | }); |
| | |
| | // 请求拦截器 |
| | instance.interceptors.request.use( |
| | (config) => { |
| | // 在发送请求之前做些什么 |
| | // 例如,从 localStorage 获取 token 并添加到请求头中 |
| | const token = localStorage.getItem('userToken'); |
| | if (token) { |
| | config.headers.Authorization = `Bearer ${token}`; |
| | } |
| | // 继续发送请求 |
| | return config; |
| | }, |
| | (error) => { |
| | // 处理请求错误 |
| | return Promise.reject(error); |
| | } |
| | ); |
| | |
| | // 响应拦截器 |
| | instance.interceptors.response.use( |
| | (response) => { |
| | // 对响应数据做点什么 |
| | // 例如,返回响应体中的数据,而不是整个响应对象 |
| | return response.data; |
| | }, |
| | (error) => { |
| | // 处理响应错误 |
| | if (error.response && error.response.status === 401) { |
| | // 如果状态码是 401,表示未授权,可能是 token 过期或无效 |
| | // 这里可以执行一些操作,比如跳转到登录页面或清除 token |
| | localStorage.removeItem('userToken'); |
| | // ...其他处理逻辑 |
| | } |
| | return Promise.reject(error); |
| | } |
| | ); |
| | |
| | // 导出配置好的 Axios 实例 |
| | export default instance; |

使用配置好的 Axios 实例发起请求

现在,你可以在其他文件中导入并使用这个配置好的 Axios 实例来发起请求:

|---|----------------------------------------------------------------|
| | import axiosInstance from './api'; // 假设你的拦截器配置在 api.js 文件中 |
| | |
| | // 发起 GET 请求 |
| | axiosInstance.get('/users') |
| | .then((users) => { |
| | console.log(users); // 处理返回的用户数据 |
| | }) |
| | .catch((error) => { |
| | console.error('Error fetching users:', error); |
| | }); |
| | |
| | // 发起 POST 请求 |
| | axiosInstance.post('/users', { name: 'John Doe' }) |
| | .then((response) => { |
| | console.log(response); // 处理创建用户的响应 |
| | }) |
| | .catch((error) => { |
| | console.error('Error creating user:', error); |
| | }); |

这样,你就配置好了 Axios 的请求拦截器和响应拦截器,并在你的应用中使用了它们。

相关推荐
光影少年5 分钟前
前端SSR和ssg区别
前端·vue.js·人工智能·学习·react.js
广州华水科技9 分钟前
北斗形变监测传感器在水库安全监测中的应用与发展
前端
凯瑟琳.奥古斯特40 分钟前
Bootstrap快速上手指南
开发语言·前端·css·bootstrap·html
精益数智工坊1 小时前
拆解制造业仓库物料管理流程:如何通过标准化仓库物料管理流程解决账实不符难题
大数据·前端·数据库·人工智能·精益工程
恶猫1 小时前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
小羊Yveesss1 小时前
2026年前端开发新趋势:智能协同、工具革新与场景深耕
前端·ai
Dxy12393102161 小时前
HTML中的Canvas可以干哪些事情
前端·html
悟乙己1 小时前
解析 Agent 时代的 HTML PPT SKILLS: html-ppt-skill
前端·html·powerpoint
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_2:(表单分组与高级输入控件实战)
前端·javascript·css·ui·html
ppandss12 小时前
JavaWeb从0到1-DAY4-AJAX
前端·ajax·okhttp