项目中如何使用axios过滤多次重复请求详解

yizhihongxing

当我们在使用axios发起多次请求时,若存在多个相同的请求,会导致冗余的网络请求,浪费带宽和服务器资源,因此,我们需要一种方法来过滤重复的请求。下面是在项目中如何使用axios过滤多次重复请求的完整攻略。

核心思路

使用axios-middleware拦截所有的请求,将每次请求的url和method做一个唯一标识,然后将这个唯一标识作为缓存中的key,将请求的promise对象存储在以该key为键的缓存中。每次请求前首先根据这个唯一标识判断缓存中是否有相同的请求,如果存在则返回缓存中的promise对象,否则执行正常的axios请求。最后将请求成功的数据传递给下一级拦截器。

详细步骤

  1. 安装axios和axios-middleware
npm install axios axios-middleware --save
  1. 在项目中引入axios和axios-middleware,并添加全局拦截器
import axios from 'axios';
import axiosMiddleware from 'axios-middleware';

axiosMiddleware(axios, {
  interceptors: {
    request: [{
        success: function ({ getState, dispatch, getSourceAction }, config) {
          // 计算请求的唯一标识,将url和method做一个唯一字符串
          const reqKey = `${config.url}_${config.method}`;

          // 判断该请求是否已经缓存了,如果已缓存则直接返回缓存中的promise对象
          if (cache[reqKey]) {
            console.log('cached', reqKey);

            return cache[reqKey];
          }

          // 否则创建一个新的promise,将该promise存储到缓存中,并返回新的promise
          const promise = new Promise((resolve, reject) => {
            axios.request(config)
              .then(res => resolve(res))
              .catch(err => reject(err));
          });
          cache[reqKey] = promise;
          console.log('cache', reqKey);

          return promise;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }],
    response: [{
        success: function ({ getState, dispatch, getSourceAction }, response) {
          return response;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }]
  }
})
  1. 在项目中使用带缓存的axios
// 此处是一个获取用户信息的请求,带上了userid作为参数
axios.get(`/api/userinfo/${userid}`).then(data => {
  console.log(data);
});

// 再次发起相同的请求,可以发现这次请求是从缓存中取得的数据
axios.get(`/api/userinfo/${userid}`).then(data => {
  console.log(data);
});

示例说明

下面通过两个简单的例子来演示如何使用axios过滤多次重复请求。

示例一

场景:在页面中有两个按钮,每个按钮点击后都会发起一个相同的网络请求。

// html
<button id="button1">Button1</button>
<button id="button2">Button2</button>

// js
const btn1 = document.querySelector('#button1');
const btn2 = document.querySelector('#button2');

btn1.addEventListener('click', () => {
  axios.get('/api/data').then(res => {
    // 处理数据...
  }).catch(err => {
    console.log(err);
  });
})

btn2.addEventListener('click', () => {
  axios.get('/api/data').then(res => {
    // 处理数据...
  }).catch(err => {
    console.log(err);
  });
})

由于两个按钮点击后都要请求相同的数据,因此会出现重复请求数据的问题。下面使用axios-middleware来解决这个问题。

import axios from 'axios';
import axiosMiddleware from 'axios-middleware';

axiosMiddleware(axios, {
  interceptors: {
    request: [{
        success: function ({ getState, dispatch, getSourceAction }, config) {
          // 计算请求的唯一标识,将url和method做一个唯一字符串
          const reqKey = `${config.url}_${config.method}`;

          // 判断该请求是否已经缓存了,如果已缓存则直接返回缓存中的promise对象
          if (cache[reqKey]) {
            console.log('cached', reqKey);

            return cache[reqKey];
          }

          // 否则创建一个新的promise,将该promise存储到缓存中,并返回新的promise
          const promise = new Promise((resolve, reject) => {
            axios.request(config)
              .then(res => resolve(res))
              .catch(err => reject(err));
          });
          cache[reqKey] = promise;
          console.log('cache', reqKey);

          return promise;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }],
    response: [{
        success: function ({ getState, dispatch, getSourceAction }, response) {
          return response;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }]
  }
})

const btn1 = document.querySelector('#button1');
const btn2 = document.querySelector('#button2');

btn1.addEventListener('click', () => {
  axios.get('/api/data').then(res => {
    // 处理数据...
  }).catch(err => {
    console.log(err);
  });
})

btn2.addEventListener('click', () => {
  axios.get('/api/data').then(res => {
    // 处理数据...
  }).catch(err => {
    console.log(err);
  });
})

示例二

场景:在table组件中,每个单元格都需要渲染相同的数据,因此会发起重复网络请求。

// html
<table>
  <tr>
    <td><div id="cell1"></div></td>
    <td><div id="cell2"></div></td>
    <td><div id="cell3"></div></td>
  </tr>
  <tr>
    <td><div id="cell4"></div></td>
    <td><div id="cell5"></div></td>
    <td><div id="cell6"></div></td>
  </tr>
  <tr>
    <td><div id="cell7"></div></td>
    <td><div id="cell8"></div></td>
    <td><div id="cell9"></div></td>
  </tr>
</table>

// js
axios.get('/api/data').then(res => {
  document.querySelector('#cell1').innerHTML = res.data;
  document.querySelector('#cell2').innerHTML = res.data;
  document.querySelector('#cell3').innerHTML = res.data;
  document.querySelector('#cell4').innerHTML = res.data;
  document.querySelector('#cell5').innerHTML = res.data;
  document.querySelector('#cell6').innerHTML = res.data;
  document.querySelector('#cell7').innerHTML = res.data;
  document.querySelector('#cell8').innerHTML = res.data;
  document.querySelector('#cell9').innerHTML = res.data;
}).catch(err => {
  console.log(err);
});

由于在渲染table中的每个单元格时都发起了相同的网络请求,因此会出现重复请求数据的问题。下面使用axios-middleware来解决这个问题。

import axios from 'axios';
import axiosMiddleware from 'axios-middleware';

axiosMiddleware(axios, {
  interceptors: {
    request: [{
        success: function ({ getState, dispatch, getSourceAction }, config) {
          // 计算请求的唯一标识,将url和method做一个唯一字符串
          const reqKey = `${config.url}_${config.method}`;

          // 判断该请求是否已经缓存了,如果已缓存则直接返回缓存中的promise对象
          if (cache[reqKey]) {
            console.log('cached', reqKey);

            return cache[reqKey];
          }

          // 否则创建一个新的promise,将该promise存储到缓存中,并返回新的promise
          const promise = new Promise((resolve, reject) => {
            axios.request(config)
              .then(res => resolve(res))
              .catch(err => reject(err));
          });
          cache[reqKey] = promise;
          console.log('cache', reqKey);

          return promise;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }],
    response: [{
        success: function ({ getState, dispatch, getSourceAction }, response) {
          return response;
        },
        error: function ({ getState, dispatch, getSourceAction }, error) {
          return Promise.reject(error);
        }
      }]
  }
})

axios.get('/api/data').then(res => {
  document.querySelector('#cell1').innerHTML = res.data;
  document.querySelector('#cell2').innerHTML = res.data;
  document.querySelector('#cell3').innerHTML = res.data;
  document.querySelector('#cell4').innerHTML = res.data;
  document.querySelector('#cell5').innerHTML = res.data;
  document.querySelector('#cell6').innerHTML = res.data;
  document.querySelector('#cell7').innerHTML = res.data;
  document.querySelector('#cell8').innerHTML = res.data;
  document.querySelector('#cell9').innerHTML = res.data;
}).catch(err => {
  console.log(err);
});

通过以上两个例子可以证明,使用axios-middleware可以有效地过滤重复的网络请求,减少浪费的带宽和服务器资源。当多个页面或组件中需要渲染相同数据时,使用axios-middleware来处理网络请求非常方便。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:项目中如何使用axios过滤多次重复请求详解 - Python技术站

(0)
上一篇 2023年5月28日
下一篇 2023年5月28日

相关文章

  • vue和webpack安装命令详解

    下面详细介绍一下如何安装 vue 和 webpack,以及相应的命令详解。 Vue.js 的安装 全局安装 可以使用以下命令全局安装 Vue CLI: npm install -g @vue/cli 如果你是 Mac 系统,并且使用了 Homebrew,则可以使用以下命令: brew install node 然后再使用全局安装命令: npm install…

    Vue 2023年5月29日
    00
  • Vue中对拿到的数据进行A-Z排序的实例

    针对“Vue中对拿到的数据进行A-Z排序的实例”的问题,我将从以下几个方面给出详细的讲解: 数据的获取与处理 排序算法的实现 渲染结果 数据的获取与处理 首先,我们需要获取到需要排序的数据。在Vue中,可以通过data属性、props属性或从后端接口获取数据。这里以从后端接口获取数据为例,假设我们已经在Vue组件中成功获取到数据,并且存储在data属性中。 …

    Vue 2023年5月29日
    00
  • vue项目配置eslint保存自动格式化问题

    下面是关于Vue项目配置ESLint保存自动格式化的完整攻略: 安装相关插件 首先,需要在Vue项目中安装eslint和eslint-plugin-prettier两个插件,可以使用npm安装,命令如下: npm install eslint eslint-plugin-prettier –save-dev 配置.eslintrc.js文件 在Vue项目的…

    Vue 2023年5月28日
    00
  • vue里的axios如何获取本地json数据

    要在Vue中使用Axios读取本地JSON文件,需要按照以下步骤进行操作: 安装Axios 在Vue项目中使用Axios,需要安装Axios。可在终端中执行以下命令进行安装: npm install axios –save 创建JSON文件 在src/assets目录中创建名为data.json的文件,并写入以下内容: { "name"…

    Vue 2023年5月28日
    00
  • Vue使用轮询定时发送请求代码

    下面我来详细讲解一下如何使用 Vue 实现轮询定时发送请求: 步骤一:安装 axios 库 要使用 Vue 实现轮询定时发送请求,首先需要安装 axios 库,通过它发送 HTTP 请求。可在命令行中输入如下命令进行安装: npm install axios –save 步骤二:编写轮询函数 根据需求,编写一个定时轮询的函数。这个函数可以使用 setInt…

    Vue 2023年5月29日
    00
  • Vue事件的基本操作你知道吗

    当我们使用Vue构建应用程序时,事件处理是至关重要的一部分。Vue提供了许多内置的指令和事件,可以让我们轻松地处理用户操作并响应状态变化。在本篇攻略中,我们将深入探讨Vue中事件的基本操作,同时提供一些示例说明,帮助读者更好地理解。 Vue事件概述 在Vue中,我们可以使用v-on指令来监听DOM事件。该指令可以添加到任何可以触发事件的HTML元素上,例如按…

    Vue 2023年5月27日
    00
  • webpack中如何加载静态文件的方法步骤

    当我们使用webpack进行前端工程化打包构建时,经常会涉及到加载静态文件的问题,包括但不限于图片、字体、音视频等多种类型的文件。接下来,我将为大家介绍 webpack 中如何加载静态文件的方法步骤。 1. 安装相关loader webpack 对于不同类型的静态文件,需要用对应的 loader 来进行加载。 以图片文件为例,可以安装 file-loader…

    Vue 2023年5月28日
    00
  • vue实现百度下拉列表交互操作示例

    具体介绍 Vue是一款MVVM(Model-View-ViewModel)框架,它的核心是实现了双向数据绑定和组件化系统。双向绑定可以使数据的修改和视图的更新同步进行,显著提高了开发效率和协作效率;组件化系统可以将页面拆分成多个独立的模块,提高代码重用性,并且允许多人协同开发大型项目。Vue的虚拟DOM机制以及其性能表现也更加优秀,使其与Angular和Re…

    Vue 2023年5月28日
    00
合作推广
合作推广
分享本页
返回顶部