Axios - understanding and use of Axios

Document description of axios: axios

Only part of and the encapsulation of axios are recorded here

catalog:

1,axios.create(config)
2. Request interception and response interception
3. Cancel interception
4. Practice of request interception and response interception

1. Create a new axios according to the specified configuration;

2. Why set create when axios() and axios.get() are directly used?

For example, there is a requirement that some interfaces in the project need to be configured differently from others. For example, a front-end application can send requests to multiple back-end applications, and baseUrl can be set differently according to create.

const instance = axios.create({
    baseUrl: 'http://location:3000'
})

// request
instance({
    url: '/getUser/xxx'
})

The request interceptor passes two functions. The successful function needs to return config, and the failed function returns Promise.reject(error)
The response interceptor passes two functions. The successful function needs to return response (result), and the failed function returns Promise.reject(error)
// Use request interceptor
axios.interceptors.request.use(config => {
    return config		// !!! Return to config configuration
}, error => {})
 
axios.interceptors.response.use(config => {
    response => {
        return response		// !! Return data
    },
    error => {
            // Request errors need to continue to be passed down
            // throw error / / method 1
            return Promise.reject(error)   // Method 2
    }
})
Multiple interceptors can be set if they are set in sequence
Interceptor sequence: request1, request2, response1, response2
Execution order: request2, request1, response1, response2

The request interceptor is added and executed first, and the response interceptor is added and executed first
(why? Source code analysis later)

Configuration process

1. Configure cancalToken object
2. Cache the cancel function used to cancel the request
3. The cancel function is actually called later to cancel the request
4. Judge in the error callback that if the error is cancel, respond

let cancel
// Send request
function getList(){
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c // c is a function used to cancel the current request
	    })
	}).then(response => {
	    // Regardless of success or failure, cancel must be set to blank. At this time, the cancellation request is invalid 
	    cancel = null
	    consolg.log('Request 1 succeeded', response.data)
	}, error => {
	    cancel = null
	    console.log('error', error)
	})
}

// Cancel request
function cancelReq () {
    // if (Object.prototype.toString.call(cancel) === "[object Function]")
    if(typeof cancel === 'function') {
        cancel() // The function that executes the cancel request
    } else {
        console.log('There are no requests to cancel')
    }
}

Send a request to cancel the previous unfinished request

Idea: judge whether cancel is a function. If yes, cancel the request and continue to send the request 2!!! Whether the request succeeds or fails, set cancel to null

function getList(){
	if (typeof cancel === 'function') {
	    Cancel('Cancel previous request')
	}
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c // c is a function used to cancel the current request
	    })
	}).then(response => {
	    // Regardless of success or failure, cancel must be set to blank. At this time, the cancellation request is invalid 
	    cancel = null
	    consolg.log('Request 1 succeeded', response.data)
	}, error => {
	    cancel = null
	    console.log('error', error)
	})
}

👆 There is a problem with this Code: click multiple times. The first request is cancelled, but the second request is not cancelled,

Reason: click send request 1, and the request of 1 will be sent immediately,
Click send request 2, and it is found that cancel is a function. Cancel will cause the error function of request 1 to execute asynchronously and be placed in the callback queue
Then send request 2. If cancel = null in the error of 1 at this time, it will cause 2 to set cancel to be empty again. Therefore, when you click the request again, you can't cancel the previous request
solve:

function getList(){
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c 
	    })
	}).then(response => {
	    cancel = null
	    consolg.log('Request 1 succeeded', response.data)
	}, error => {
	    //!!  error may be of type cancel. If the request is cancelled, here is the message returned
	    if(axios.isCancel(error)) {	
	        console.log('Cancellation request failed', error.message)
	    } else {
	        cancel = null
	        console.log('request was aborted', error.message)
	    }
	})
}

That's all for the cancellation request

If you use the above code to send a request, you need to write a large amount of code similar to getList for each request – > request interception and response interception

let cancel 
function getList1 () {
    axios({
        url: 'http://localhost:9999',
    }).then(response => {
        consolg.log('Request 1 succeeded', response.data)
    }, error => {
        console.log('request was aborted', error.message)
    })
}

// Use request interceptor
axios.interceptors.request.use(config => {
    if(typeof cancel === 'function') {
        cancel()    // The function that executes the cancel request
    }
    config.cancelToken = new axios.CancelToken(c => {
        cancel = c  //  c is a function used to cancel the current request
    })
    return config
}, error => {})
 
axios.interceptors.response.use(config => {
    response => {
        cancel = null   
        return response
    },
    error => {
        if(axios.isCancel(error)) {     // Error canceling request 
            console.log('Cancellation request failed', error.message)
            // Interrupt promise chain
            return new Promise(() => {})
        } else {
            cancel = null   
            console.log('request was aborted', error.message)
            // Request errors need to continue to be passed down
            // throw error / / method 1
            return Promise.reject(error)   // Method 2
        }
    }
})

function cancelReq () {
    // if (Object.prototype.toString.call(cancel) === "[object Function]")
    if(typeof cancel === 'function') {
        cancel()    // The function that executes the cancel request
    } else {
        console.log('There are no requests to cancel')
    }
}

Tags: Javascript Front-end

Posted on Fri, 03 Dec 2021 07:38:58 -0500 by OpSiS