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

相关推荐
Vicky&James9 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_7482336412 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟21 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386321 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596022 分钟前
前端代理,解决跨域问题讲解
前端
quitv27 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238136 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星38 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端