In Axios, you can monitor the download progress during GET requests by utilizing the onDownloadProgress property. This property enables you to define a handler function that receives a ProgressEvent object as a parameter. This object provides information about the request progress, including the number of bytes downloaded and the total bytes.
Here is an example demonstrating how to use onDownloadProgress to track download progress:
javascriptaxios.get('/your-endpoint', { onDownloadProgress: function(progressEvent) { // The `progressEvent` object contains the `loaded` and `total` properties // `loaded` represents the number of bytes already downloaded // `total` is the total number of bytes in the response (if the `Content-Length` header is set) if (progressEvent.lengthComputable) { // Calculate progress percentage const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`Download progress: ${percentCompleted}%`); } else { // Cannot compute progress (no total length information) console.log(`Downloaded ${progressEvent.loaded} bytes`); } } }) .then(response => { // Handling after successful request console.log(`Download complete`, response); }) .catch(error => { // Handling request failure console.error(`Download error`, error); });
In this example, when a GET request is initiated, Axios periodically invokes the onDownloadProgress function and passes a ProgressEvent object containing the progress information. Within this function, you can extract the progress information and implement any required logic, such as updating the UI to display a progress bar.
Note that the reliability of the progress information depends on the server providing the correct Content-Length header. If this header is missing or incorrectly configured, progressEvent.total will be 0, preventing the calculation of the exact progress percentage. In such cases, you can only display the number of bytes downloaded, without being able to show a specific progress bar.