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 的请求拦截器和响应拦截器,并在你的应用中使用了它们。

相关推荐
gs8014023 分钟前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript
岁岁种桃花儿1 小时前
Vue核心语法第一篇:Vue是什么?
前端·javascript·vue.js
观无2 小时前
若依EasyExcel实现单元格合并
开发语言·前端·javascript
愚公搬代码2 小时前
【愚公系列】《Web应用安全》001-VMware的安装
前端·安全
xiaohaiAIgeo2 小时前
【2026年】HG/T 20656-2024化工暖通空调设计规范:新版标准的变化与影响
java·前端·javascript·科普知识
立少→万能汉编2 小时前
用“立少→超文本”写静态网页,标签<倍>
服务器·前端·javascript
weixin_431600442 小时前
NestJS 入门(7):生命周期钩子——构造函数和 `OnModuleInit` 差在哪?
前端·后端·学习·node.js·nest.js
你挚爱的强哥3 小时前
【chromeDownload】自定义组件:多用于登录框底部提供下载Chrome谷歌浏览器的链接
前端·vue.js·chrome
cindershade3 小时前
用原生 HTML5 视频与 Canvas 实现浏览器端视频抽帧封面
前端
笨鸟先飞,勤能补拙3 小时前
Web 服务器与计算机网络全景原理
运维·服务器·前端·网络·人工智能·计算机网络·web安全