axios拦截器(interceptors)和取消请求(cancelToken)

阻截器

web向后端传输数据的两种格式json和urlencoded
import qs from ‘qs’
data: qs.stringify(data)
因此需要判断到底传入的是什么类型的数据
因此就需要用到axios阻截器可以修改一下类型

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

这是请求阻截器,在请求发生之前作一些操作例如可以是所有的json转换为urlencoded。
例如把data{
username:“tom”,
password:“123456”
} 转换为 username=tom&password=123456形式

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    const {data,method} = config;
    if(method.toLowerCase() === 'post' && typeof data === 'object'){
		config.data = qs.stringify(data);
	}
    return config;
  }

顾名思义还有一个响应拦截器

axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

可以过滤掉一些从后端返回的信息,还可以统一处理请求错误的信息

return new Promise(() => {});

axios取消请求

    const CancelToken = axios.CancelToken
    let cancel
    axios.defaults.baseURL = 'http://localhost:3000'
    axios.get('/comments', {
        cancelToken: new CancelToken((c) => {
            //保存取消到外部,用于取消请求
            cancel = c;
        })
    }).then((result) => {
        console.log(result)
    }).catch((err) => {
        console.log(err)
    });
    cancel('已取消')

这个如果我们要实现一种效果 就是 两个按钮 点击一个按钮会发一次请求,如果点了一个按钮 ,在响应返回前点下另一个按钮,上一个请求取消,只执行当前的请求。

    const CancelToken = axios.CancelToken

    let cancel
    axios.defaults.baseURL = 'http://localhost:3000'
    testReq1 = () => {
        cancel && cancel('请求已取消')

        axios.get('/comments', {
            cancelToken: new CancelToken((c) => {
                //保存取消到外部,用于取消请求
                cancel = c;
            })
        }).then((result) => {
            cancel = null
            console.log(result)
        }).catch((err) => {
            if (axios.isCancel(err)) {
                console.log('request cancel',err)
            } else {
                cancel = null
                console.log('request err ',err)
            }
        });
    }
    testReq2 = () => {
        cancel && cancel('请求已取消')

        axios.get('/comments', {
            cancelToken: new CancelToken((c) => {
                //保存取消到外部,用于取消请求
                cancel = c;
            })
        }).then((result) => {
            cancel = null
            console.log(result)
        }).catch((err) => {
            if (axios.isCancel(err)) {
                console.log('request cancel',err)
            } else {
                cancel = null
                console.log('request err ',err)
            }
        });

    }
    testCancel = () => {
        cancel && cancel('请求已取消')
    }

这个我们可以看出 代码大量相似,这个时候 就可以用到拦截器。
在请求前 把指定的cancel清除,在相应拦截器中

    const CancelToken = axios.CancelToken

    let cancel
    axios.defaults.baseURL = 'http://localhost:3000'

    axios.interceptors.request.use(config => {
        if (typeof cancel == 'function') {
            cancel('请求已取消')
        }
        // 配置当前的cancelToken 保存cancel
        config.cancelToken = new CancelToken((c) => {
            cancel = c
        })
        return config
    })
    axios.interceptors.response.use(res => {
        console.log(typeof res)
        cancel = null
        return res
    }, err => {
        if (axios.isCancel(err)) {
            console.log( 'request cancel ', err.message)
            return new Promise(() =>{})
        }
        cancel = null
        return Promise.reject(err)
    })
    testReq1 = () => {
        axios.get('/comments').then((result) => {
            console.log(result)
        }).catch((err) => {
            console.log('request cancel', err)
        });
    }
    testReq2 = () => {
        axios.get('/comments').then((result) => {
            console.log(result)
        }).catch((err) => {
            console.log('request cancel', err)
        });

    }
    testCancel = () => {
        cancel && cancel('请求已取消')
    }

  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值