axios study notes (1)

First, create an instance object

Access different background links and use different instance objects to send requests 

// 创建实例对象
const requestA = axios.create({
    baseURL: '',  // 基础访问路径 http://localhost:3000
    timeout: 10000, // 设置超时时间

})

// 创建实例对象
const requestB = axios.create({
    baseURL: '',  // 基础访问路径 http://b.com
    timeout: 10000, // 设置超时时间

})


//使用 request与axios对象的功能 几乎一样
requestA.get('/post').then(res=>{
    console.log(res)
})

Second, set the request interceptor

For request preprocessing, you can modify the settings for sending the request. The trigger sequence is first-in, last-out , and write first and then verify.

requestA.interceptors.request.use(
    config=>{
        return config
    },
    error=>{
        return Promise.reject(error)
    }
)

The configuration can be modified in config=>{}, such as:

config.timeout=2000 

config.params={a:100} -----> The request url becomes: http://localhost:3000/post?a=100

The token verified in the background is generally added to the request configuration at this time. 

Third, set the response interceptor

The preprocessing of the background response results can simplify the res data in axios().then(res=>{})

The trigger sequence is first-in, first- out , first-to-write first-to-modify.

requestA.interceptors.response.use(
    response=>{
        return response
    },
    error=>{
        return Promise.reject(error)
    }
)

4. Cancellation request

Click the request button multiple times, if the previous request has not been completed, cancel the previous request and send this request

// 定义全局变量
let cancel = null

//给按钮添加点击事件
btn.onclick = function(){

    //检测上次请求是否完成
    if(cancel !== null){
        cancel()  // 调用cancel函数,取消上一次请求
    }

    axios.get(
        'http://localhost:3000/posts',
       
        { // 添加配置对象的属性
            cancelToken: new axios.CancelToken(function(c){
                // 将c的值赋值给cancel
                cancel = c
            })
        }
    ).then(res => {
        console.log(res)
        // 请求完成,将cancel初始化
        cancel = null
}

 

Guess you like

Origin blog.csdn.net/weixin_59128282/article/details/121658220