如何从Axios获取响应时间

67up9zun  于 2022-11-23  发布在  iOS
关注(0)|答案(9)|浏览(637)

有没有人能提供一些从Axios获得响应时间的方法?我发现了Axios计时,但我并不喜欢它(我知道这是有争议的)。我只是想知道是否有人找到了记录响应时间的好方法。

ddhy6vgd

ddhy6vgd1#

您可以使用axios的拦截器概念。
请求拦截器将设置startTime

axios.interceptors.request.use(function (config) {
 
  config.metadata = { startTime: new Date()}
  return config;
}, function (error) {
  return Promise.reject(error);
});

响应拦截器将设置endTime并计算持续时间

axios.interceptors.response.use(function (response) {
 
  response.config.metadata.endTime = new Date()
  response.duration = response.config.metadata.endTime - response.config.metadata.startTime
  return response;
}, function (error) {
  error.config.metadata.endTime = new Date();
  error.duration = error.config.metadata.endTime - error.config.metadata.startTime;
  return Promise.reject(error);
});
sh7euo9m

sh7euo9m2#

这是我的解决方案,通过在拦截器中设置头:

import axios from 'axios'

const url = 'https://example.com'

const instance = axios.create()

instance.interceptors.request.use((config) => {
    config.headers['request-startTime'] = process.hrtime()
    return config
})

instance.interceptors.response.use((response) => {
    const start = response.config.headers['request-startTime']
    const end = process.hrtime(start)
    const milliseconds = Math.round((end[0] * 1000) + (end[1] / 1000000))
    response.headers['request-duration'] = milliseconds
    return response
})

instance.get(url).then((response) => {
    console.log(response.headers['request-duration'])
}).catch((error) => {
    console.error(`Error`)
})
q9yhzks0

q9yhzks03#

在@user3653268上捎带--我修改了他们的答案,以便与react钩子一起使用,并使用模来显示x.xxx秒数。

import React, { useState } from 'react';
import axios from 'axios';

export default function Main() {
  const [axiosTimer, setAxiosTimer] = useState('');

  const handleSubmit = () => {
      let startTime = Date.now();
      axios.post('urlstuff')
      .then(response => {
          console.log('handleSubmit response: ', response);
          axiosTimerFunc(startTime);
      })
      .catch(err => {
          console.log("handleSubmit error:", err.response.data.message)
          axiosTimerFunc(startTime);
          setLoading(false);
      });
    }

  const axiosTimerFunc = (startTime) => {
    let now = Date.now();
    let seconds = Math.floor((now - startTime)/1000);
    let milliseconds = Math.floor((now - startTime)%1000);
    setAxiosTimer(`${seconds}.${milliseconds} seconds`);
  }

  return(
     <div>
        <h2>Load Time: {axiosTimer}</h2>
     </div>
  )
}
i7uq4tfw

i7uq4tfw4#

下面是另一种方法:

const instance = axios.create() 

instance.interceptors.request.use((config) => {
  config.headers['request-startTime'] = new Date().getTime();
  return config
})

instance.interceptors.response.use((response) => {
  const currentTime = new Date().getTime()      
  const startTime = response.config.headers['request-startTime']      
  response.headers['request-duration'] = currentTime - startTime      
  return response
})

instance.get('https://example.com')
  .then((response) => {      
    console.log(response.headers['request-duration'])
  }).catch((error) => {
    console.error(`Error`)
  })
mbskvtky

mbskvtky5#

使用async \ await可以轻松地完成此操作,但并不理想:

const start = Date.now()
await axios.get(url)
const finish = Date.now()

const time = (finish - start) / 1000

这将是关于axios调用的时间。不是那么理想,但显示和易于实现

yzckvree

yzckvree6#

另一个简单的方法是:

axios.interceptors.response.use(
  (response) => {
    console.timeEnd(response.config.url);
    return response;
  },
  (error) => {
    console.timeEnd(error.response.config.url); 
    return Promise.reject(error);
  }
);

axios.interceptors.request.use(
  function (config) {
    console.time(config.url );
    return config;
}, function (error) {
    return Promise.reject(error);
});
whhtz7ly

whhtz7ly7#

它的方式很久以后,但这是我的简单变通办法

function performSearch() {
        var start = Date.now();
        var url='http://example.com';
        var query='hello';
        axios.post(url,{'par1':query})
            .then(function (res) {
                var millis = Date.now() - start;
                $('.timer').html(""+Math.floor(millis/1000)+"s")
            })
            .catch(function (res) {
                console.log(res)
            })

    }

这是我解决方法

vaj7vani

vaj7vani8#

实际上,您可以通过“x-response-time”头来获得它,该头是从axios请求的响应中获得的

axios({
          method: 'GET',
          url: 'something.com',

        })
          .then((response) => {
            console.log(response.headers['x-response-time']);
          })
bvpmtnay

bvpmtnay9#

NOT WORKING EXAMPLE
假设我想管理和导入拦截器,我想在单独的文件logTimeInterceptor.js中定义它们:

export const responseTimeInterceptor = (response) => {
  // to avoid overwriting if another interceptor
  // already defined the same object (meta)
  response.meta = response.meta || {}
  response.meta.requestStartedAt = new Date().getTime()
  return response
}

export const logResponseTimeInterceptor = ((response) => {
    // Logs response time - only for successful requests
    console.log(
      `📡 API | Execution time for: ${response.config.url} - ${
        new Date().getTime() - response.config.meta.requestStartedAt
      } ms`
    )
    return response
  },
  // Support for failed requests
  // Handle 4xx & 5xx responses
  (response) => {
    console.error(
      `📡 API | Execution time for: ${response.config.url} - ${
        new Date().getTime() - response.config.meta.requestStartedAt
      } ms`
    )
    throw response
  }
)

然后我导入它们,并以httpClient.js的给定示例的方式使用它们:

import axios from 'axios'
import { ApiSettings } from '@/api/config'
import {
  responseTimeInterceptor,
  logResponseTimeInterceptor
} from '@/api/interceptors/logTimeInterceptor'

// ==============    A P I   C L I E N T    =============
const httpClient = axios.create(ApiSettings)

// ============== A P I   I N T E R C E P T O R S =============
httpClient.interceptors.request.use(authInterceptor)
httpClient.interceptors.response.use(
  responseTimeInterceptor,
  logResponseTimeInterceptor,
)

export default httpClient

但是这些拦截器不能作为导入一起工作,我认为它们必须在httpClient文件中保持完整。

相关问题