In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge I am facing is that the time value I receive under request-duration
is only available after the request has been responded to, which is not what I need. I want to capture the time either before or during the call to the webservice. Complicating matters further is the fact that the method I invoke is located in a separate file: Request.js
export const getRequest = async (url, baseURL, headers) => {
const HTTP = axios.create({
baseURL,
headers,
});
HTTP.interceptors.request.use((config) => {
config.headers["request-startTime"] = new Date().getTime();
return config;
});
HTTP.interceptors.response.use((response) => {
const currentTime = new Date().getTime();
const startTime = response.config.headers["request-startTime"];
response.headers["request-duration"] = currentTime - startTime;
return response;
});
return HTTP.get(url);
};
Users.vue
async getUsers() {
try {
let url = `/users`;
let baseUrl = `baseURL`;
let headers = {};
const responseUsers = await getRequest(url,baseUrl,headers);
console.log(responseJobTasks.headers["request-duration"]); //displays the time in milliseconds here
if (responseJobTasks.status === 200) {
const { data } = responseJobTasks;
this.users = data;
}
} catch (error) {
console.error(error);
}
}