乐闻世界logo
搜索文章和话题

How to get response times from Axios

1个答案

1

When making network requests with Axios, you can measure the response time using several approaches. Below, I will explain step by step how to achieve this.

Method 1: Using Axios Interceptors

Axios interceptors are a powerful feature that enable you to intervene during request initiation and response handling. By using interceptors, you can record a timestamp before sending the request and another timestamp after receiving the response, then compute the difference to determine the response time.

Here is a simple example:

javascript
// First, create an Axios instance const axiosInstance = axios.create(); // Add a request interceptor axiosInstance.interceptors.request.use(config => { // Before sending the request, add a custom property startTime to record the start time config.metadata = { startTime: new Date() }; return config; }, error => { // Handle request errors return Promise.reject(error); }); // Add a response interceptor axiosInstance.interceptors.response.use(response => { // After receiving the response, retrieve the start time const startTime = response.config.metadata.startTime; // Calculate the response time response.duration = new Date() - startTime; return response; }, error => { // Handle response errors return Promise.reject(error); }); // Use this Axios instance to make a request axiosInstance.get('https://api.example.com/data') .then(response => { console.log(`Request response time: ${response.duration}ms`); }) .catch(error => { console.error('Request error', error); });

In this example, we first create a new Axios instance. We add a request interceptor that attaches a custom metadata property to the request object, setting startTime to record the request initiation time. Then we add a response interceptor where we retrieve startTime from response.config.metadata and calculate the duration, storing it as response.duration.

Method 2: Using Axios Request Configuration Options

Alternatively, you can directly record the start and end times of the request when making the request through Axios request configuration options:

javascript
// Record the start time const startTime = new Date(); axios.get('https://api.example.com/data') .then(response => { // Calculate the response time const duration = new Date() - startTime; console.log(`Request response time: ${duration}ms`); }) .catch(error => { console.error('Request error', error); });

This method is straightforward and direct. However, if you need to reuse this logic across multiple requests, using interceptors is preferable as it avoids duplicating the same code in each request.

2024年6月29日 12:07 回复

你的答案