You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用Axios发起API请求时如何统计响应时间

如何统计Axios请求的耗时?

嘿,我来给你几种简单可行的方案,帮你统计这个API请求的耗时:

方案1:手动记录时间戳(适合单个请求)

这是最直接的方式,在发起请求前记录一个时间点,拿到响应后再记录一个,两者的差值就是请求耗时。推荐用performance.now(),它比Date.now()精度更高(能精确到微秒级别)。

修改你的代码如下:

const fetch_table_data = async () => { 
  // 记录请求开始时间
  const startTime = performance.now();
  
  const response = await axios.get(`URL_HERE`, {headers : {'Authorization': 'Token abc'}});
  
  if (response.status === 200){ 
    // 计算耗时
    const timeTaken = performance.now() - startTime;
    console.log(`请求耗时:${timeTaken} 毫秒`);
    // 也可以把这个耗时存起来用于后续业务逻辑
  }
} 
fetch_table_data()

方案2:使用Axios拦截器(适合全局统一统计)

如果你的项目里有很多Axios请求,不想每个请求都重复写计时代码,可以用Axios的请求/响应拦截器来全局处理,一次配置所有请求都能自动统计耗时:

// 添加请求拦截器,记录每个请求的开始时间
axios.interceptors.request.use(function (config) {
  config.startTime = performance.now();
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 添加响应拦截器,计算并记录耗时
axios.interceptors.response.use(function (response) {
  const timeTaken = performance.now() - response.config.startTime;
  console.log(`请求 ${response.config.url} 耗时:${timeTaken} 毫秒`);
  // 把耗时挂载到response对象上,方便后续业务直接取用
  response.timeTaken = timeTaken;
  return response;
}, function (error) {
  // 即使请求失败,也可以统计耗时
  if (error.config?.startTime) {
    const timeTaken = performance.now() - error.config.startTime;
    console.log(`请求 ${error.config.url} 失败,耗时:${timeTaken} 毫秒`);
  }
  return Promise.reject(error);
});

// 原有代码无需改动,就能自动获取耗时
const fetch_table_data = async () => { 
  const response = await axios.get(`URL_HERE`, {headers : {'Authorization': 'Token abc'}});
  if (response.status === 200){ 
    // 直接通过response.timeTaken拿到耗时
    console.log('请求耗时:', response.timeTaken);
  }
} 
fetch_table_data()

小调试技巧

如果只是临时查看请求耗时,其实不用写代码——打开浏览器的开发者工具(Network面板),就能直接看到每个请求的详细耗时数据,包括等待时间、下载时间等细分项,快速又直观~

内容的提问来源于stack exchange,提问作者Mahesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:12:31