经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » iOS » 查看文章
一篇文章带你详细了解axios的封装 - 公众号-web前端进阶
来源:cnblogs  作者:公众号-web前端进阶  时间:2023/6/5 14:53:46  对本文有异议

axios 封装

对请求的封装在实际项目中是十分必要的,它可以让我们统一处理 http 请求。比如做一些拦截,处理一些错误等。本篇文章将详细介绍如何封装 axios 请求,具体实现的功能如下

  • 基本配置

    配置默认请求地址,超时等

  • 请求拦截

    拦截 request 请求,处理一些发送请求之前做的处理,譬如给 header 加 token 等

  • 响应拦截

    统一处理后端返回的错误

  • 全局 loading

    为所有请求加上全局 loading(可配置是否启用)

  • 取消重复请求

当同样的请求还没返回结果再次请求直接取消

基础配置

这里以 vue3 为例,首先安装 axios,element-plus

  1. npm i axios element-plus

在 src 下新建 http/request.ts 目录用于写我们的封装逻辑,然后调用 aixos 的 create 方法写一些基本配置

  1. import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
  2. const service = axios.create({
  3. method: 'get',
  4. baseURL: import.meta.env.VITE_APP_API, //.env中的VITE_APP_API参数
  5. headers: {
  6. 'Content-Type': 'application/json;charset=utf-8',
  7. },
  8. timeout: 10000, //超时时间
  9. });
  10. export default service;

这样便完成了 aixos 的基本配置,接下来我们可以在 http 下新建 api 目录用于存放我们接口请求,比如在 api 下创建 login.ts 用于写登录相关请求方法,这里的/auth/login我已经用 nestjs 写好了

  1. import request from './request';
  2. export const login = (data: any) => {
  3. return request({
  4. url: '/auth/login',
  5. data,
  6. method: 'post',
  7. });
  8. };

然后可以在页面进行调用

  1. <script lang="ts" setup>
  2. import { login } from '@/http/login';
  3. const loginManage = async () => {
  4. const data = await login({
  5. username: '鸡哥哥',
  6. password: '1234',
  7. });
  8. console.log(data);
  9. };
  10. loginManage();
  11. </script>

结果打印如下

image.png

响应拦截器

我们可以看到返回的数据很多都是我们不需要的,我们需要的只有 data 中的数据,所以这时候我们便需要一个响应拦截器进行处理,同时在响应拦截器中我们不仅仅简单处理这个问题,还需要对后端返回的状态码进行判断,如果不是正确的状态码可以弹窗提示后端返回的描述(也可以自定义)

  1. service.interceptors.response.use(
  2. (res: AxiosResponse<any, any>) => {
  3. const { data } = res;
  4. if (data.code != 200) {
  5. ElMessage({
  6. message: data.describe,
  7. type: 'error',
  8. });
  9. if (data.code === 401) {
  10. //登录状态已过期.处理路由重定向
  11. console.log('loginOut');
  12. }
  13. throw new Error(data.describe);
  14. }
  15. return data;
  16. },
  17. (error) => {
  18. let { message } = error;
  19. if (message == 'Network Error') {
  20. message = '后端接口连接异常';
  21. } else if (message.includes('timeout')) {
  22. message = '系统接口请求超时';
  23. } else if (message.includes('Request failed with status code')) {
  24. message = '系统接口' + message.substr(message.length - 3) + '异常';
  25. }
  26. ElMessage({
  27. message: message,
  28. type: 'error',
  29. });
  30. return Promise.reject(error);
  31. },
  32. );

这里规定后台 code 不是 200 的请求是异常的,需要弹出异常信息(当然这里由自己规定),同时 401 状态表示登录已过期,如果你需要更多的异常处理都可以写在这里。注意这里都是对 code 状态码的判断,这表示后台返回的 http 的 status 都是 2xx 才会进入的逻辑判断,如果后台返回 status 异常状态码比如 4xx,3xx 等就会进入 error 里,可以在 error 里进行逻辑处理,这里要和后端小朋友约定好

请求拦截器

请求请求拦截器和响应拦截器类似,只不过是在请求发送之前我们需要做哪些处理,它的用法如下

  1. service.interceptors.request.use(
  2. (config: InternalAxiosRequestConfig<any>) => {
  3. console.log(config);
  4. return config;
  5. },
  6. (error) => {
  7. console.log(error);
  8. },
  9. );

image.png

我们可以看到 config 中包含了我们请求的一些信息像 headers,data 等等,我们是可以在这里对其进行修改的,比如我们在 headers 加一个 token

  1. declare module "axios" {
  2. interface InternalAxiosRequestConfig<D = any, T = any> {
  3. isToken?: boolean;
  4. }
  5. }
  6. declare module "axios" {
  7. interface AxiosRequestConfig<D = any> {
  8. isToken?: boolean;
  9. }
  10. }
  11. service.interceptors.request.use(
  12. (config: InternalAxiosRequestConfig<any>) => {
  13. const { isToken = true } = config;
  14. if (localStorage.getItem('token') && !isToken) {
  15. config.headers['Authorization'] =
  16. 'Bearer ' + localStorage.getItem('token'); // 让每个请求携带自定义token 请根据实际情况自行修改
  17. }
  18. return config;
  19. },
  20. (error) => {
  21. console.log(error);
  22. },
  23. );

这里假设用户登录成功将 token 缓存到了 localStorage 中,接口是否需要 token 则是在请求的时候自己配置,比如 login 接口不加 token,注意这里需要给InternalAxiosRequestConfigAxiosRequestConfig加上自定义的字段,否则 TS 会报错

  1. export const login = (data: any) => {
  2. return request({
  3. url: '/auth/login',
  4. data,
  5. isToken: false,
  6. method: 'post',
  7. });
  8. };

image.png

此时我们可以获取到 config 中的 isToken 了

添加全局 loading

我们通常会在请求开始前加上 loading 弹窗,请求结束再进行关闭,实现其实很简单,在请求拦截器中调用 ElLoading.service 实例,响应拦截器中 close 即可。但是这样会出现一个问题,

当多个请求进入会开启多个 loading 实例吗? 这倒不会,因为在 element-plus 中的 ElLoading.service()是单例模式,只会开启一个 loading。

上述问题虽然不需要我们考虑,但是还有一个问题

同时进来多个请求,此时 loading 已经开启,假设 1 秒后多个请求中其中一个请求请求完成,按照上述逻辑会执行 close 方法,但是还有请求未完成 loading 却已经关闭,显然这不符合我们的期望

因此,我们可以定义一个变量用于记录正在请求的数量,当该变量为 1 时开启 loading,当变量为 0 时关闭 loading,同样的我们还定义了 config 中的 loading 让开发者自己决定是否开启 loading,实现如下

  1. let requestCount = 0;
  2. const showLoading = () => {
  3. requestCount++;
  4. if (requestCount === 1) loadingInstance();
  5. };
  6. const closeLoading = () => {
  7. requestCount--;
  8. if (requestCount === 0) loadingInstance().close();
  9. };
  10. service.interceptors.request.use(
  11. (config: InternalAxiosRequestConfig<any>) => {
  12. const { loading = true, isToken = true } = config;
  13. return config;
  14. },
  15. (error) => {
  16. console.log(error);
  17. },
  18. );
  19. service.interceptors.response.use(
  20. (res: AxiosResponse<any, any>) => {
  21. const { data, config } = res;
  22. const { loading = true } = config;
  23. if (loading) closeLoading();
  24. },
  25. (error) => {
  26. closeLoading();
  27. return Promise.reject(error);
  28. },
  29. );

取消重复请求

当同样的请求还没返回结果再次请求我们需要直接取消这个请求,通常发生在用户连续点击然后请求接口的情况,但是如果加了 loading 这种情况就不会发生。axios 中取消请求可以使用AbortController,注意这个 api 需要 axios 版本大于 v0.22.0 才可使用,低版本可以使用CancelToken,下面看一下AbortController使用方法

  1. service.interceptors.request.use(
  2. (config: InternalAxiosRequestConfig<any>) => {
  3. const controller = new AbortController();
  4. const { loading = true, isToken = true } = config;
  5. config.signal = controller.signal;
  6. controller.abort();
  7. return config;
  8. },
  9. (error) => {
  10. console.log(error);
  11. },
  12. );

这里是将 controller 的 signal 赋值给 config 的 sigal,然后执行 controller 的 abort 函数即可取消请求

image.png

知道了如何取消 axios 请求,接下来我们就可以写取消重复请求的逻辑了

当拦截到请求的时候,将 config 中的 data,url 作为 key 值,AbortController 实例作为 value 存在一个 map 中,判断是否 key 值是否存在来决定是取消请求还是保存实例

  1. const requestMap = new Map();
  2. service.interceptors.request.use(
  3. (config: InternalAxiosRequestConfig<any>) => {
  4. const controller = new AbortController();
  5. const key = config.data + config.url;
  6. config.signal = controller.signal;
  7. if (requestMap.has(key)) {
  8. requestMap.get(key).abort();
  9. requestMap.delete(key);
  10. } else {
  11. requestMap.set(key, controller);
  12. }
  13. return config;
  14. },
  15. (error) => {
  16. console.log(error);
  17. },
  18. );

我们短时间内发送两次请求就会发现有一个请求被取消了

到这里基本就完成了 axios 的封装,下面是完整代码,直接 CV,就可以摸鱼一整天~

  1. import axios, {
  2. AxiosInstance,
  3. AxiosResponse,
  4. InternalAxiosRequestConfig,
  5. } from "axios";
  6. import { ElMessage, ElLoading } from "element-plus";
  7. const loadingInstance = ElLoading.service;
  8. let requestCount = 0;
  9. const showLoading = () => {
  10. requestCount++;
  11. if (requestCount === 1) loadingInstance();
  12. };
  13. const closeLoading = () => {
  14. requestCount--;
  15. if (requestCount === 0) loadingInstance().close();
  16. };
  17. const service: AxiosInstance = axios.create({
  18. method: "get",
  19. baseURL: import.meta.env.VITE_APP_API,
  20. headers: {
  21. "Content-Type": "application/json;charset=utf-8",
  22. },
  23. timeout: 10000,
  24. });
  25. //请求拦截
  26. declare module "axios" {
  27. interface InternalAxiosRequestConfig<D = any, T = any> {
  28. loading?: boolean;
  29. isToken?: boolean;
  30. }
  31. }
  32. declare module "axios" {
  33. interface AxiosRequestConfig<D = any> {
  34. loading?: boolean;
  35. isToken?: boolean;
  36. }
  37. }
  38. const requestMap = new Map();
  39. service.interceptors.request.use(
  40. (config: InternalAxiosRequestConfig<any>) => {
  41. const controller = new AbortController();
  42. const key = config.data + config.url;
  43. config.signal = controller.signal;
  44. if (requestMap.has(key)) {
  45. requestMap.get(key).abort();
  46. requestMap.delete(key);
  47. } else {
  48. requestMap.set(key, controller);
  49. }
  50. console.log(123);
  51. const { loading = true, isToken = true } = config;
  52. if (loading) showLoading();
  53. if (localStorage.getItem("token") && !isToken) {
  54. config.headers["Authorization"] =
  55. "Bearer " + localStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
  56. }
  57. return config;
  58. },
  59. (error) => {
  60. console.log(error);
  61. }
  62. );
  63. service.interceptors.response.use(
  64. (res: AxiosResponse<any, any>) => {
  65. const { data, config } = res;
  66. const { loading = true } = config;
  67. if (loading) closeLoading();
  68. if (data.code != 200) {
  69. ElMessage({
  70. message: data.describe,
  71. type: "error",
  72. });
  73. if (data.code === 401) {
  74. //登录状态已过期.处理路由重定向
  75. console.log("loginOut");
  76. }
  77. throw new Error(data.describe);
  78. }
  79. return data;
  80. },
  81. (error) => {
  82. closeLoading();
  83. let { message } = error;
  84. if (message == "Network Error") {
  85. message = "后端接口连接异常";
  86. } else if (message.includes("timeout")) {
  87. message = "系统接口请求超时";
  88. } else if (message.includes("Request failed with status code")) {
  89. message = "系统接口" + message.substr(message.length - 3) + "异常";
  90. }
  91. ElMessage({
  92. message: message,
  93. type: "error",
  94. });
  95. return Promise.reject(error);
  96. }
  97. );
  98. export default service;

微信扫码关注公众号web前端进阶每日更新最新前端技术文章,你想要的都有!

原文链接:https://www.cnblogs.com/zdsdididi/p/17456991.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号