Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response times from Axios

Tags:

axios

Can anyone suggest any ways to get response times from Axios? I've found axios-timing but I don't really like it (controversial, I know). I'm just wondering if anyone else has found some good ways to log response times.

like image 504
rozza Avatar asked Apr 17 '18 09:04

rozza


People also ask

How do I get an Axios post response?

Axios Post Request The response is provided as a promise because Axios GitHub is promise-based. To obtain the response and catch any errors, we must utilize the then() and catch() functions.

What is Axios response data?

Axios Response object data - the payload returned from the server. status - the HTTP code returned from the server. statusText - the HTTP status message returned by the server. headers - headers sent by server. config - the original request configuration.

What can I use instead of Axios?

redux-saga, GraphQL, jQuery, Modernizr, and Modernizr are the most popular alternatives and competitors to axios.


2 Answers

You can use the interceptor concept of axios.

Request interceptor will set startTime

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

Response interceptor will set endTime & calculate the duration

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); }); 
like image 148
Sagar M Avatar answered Oct 20 '22 00:10

Sagar M


This is my solution, by setting the header in the interceptor:

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`) }) 
like image 36
patrick-fitzgerald Avatar answered Oct 20 '22 02:10

patrick-fitzgerald