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.
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.
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.
redux-saga, GraphQL, jQuery, Modernizr, and Modernizr are the most popular alternatives and competitors to axios.
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); });
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`) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With