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

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95274 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大4 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师4 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学4 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端