赞
踩
在日常开发中我们有时候会有需求,去取消一个接口的请求,那么如何取消接口请求?
- const controller = new AbortController();
-
- axios.get('/foo/bar', {
- signal: controller.signal
- }).then(function(response) {
- //...
- });
- // 取消请求 不可传递参数
- controller.abort()
- const CancelToken = axios.CancelToken;
- const source = CancelToken.source();
-
- axios.get('/user/12345', {
- cancelToken: source.token
- }).catch(function (thrown) {
- if (axios.isCancel(thrown)) {
- console.log('Request canceled', thrown.message);
- } else {
- // 处理错误
- }
- });
-
- axios.post('/user/12345', {
- name: 'new name'
- }, {
- cancelToken: source.token
- })
-
- // 取消请求(message 参数是可选的)
- source.cancel('Operation canceled by the user.');
- export function allListAPI(params,option) {
- return request({
- url: '/url',
- method: 'get',
- params,
- ...option
- })
- }
- const CancelToken = axios.CancelToken;
- const source = CancelToken.source();
-
- allListAPI( Params,{
- cancelToken : source.token
- }).then(res=>{
-
- }).catch(err=>{
- console.log(err,'err')
- })
- source.cancel('取消请求时传递的信息');
控制台输出:
- controller=new AbortController()
-
- allListAPI( Params,{
- signal : controller.signal
- }).then(res=>{
-
- }).catch(err=>{
- console.log(err,'err')
- })
- this.controller.abort(); //不可传递参数
控制台输出:
下边引用官网示例代码,参考上方取消单个接口请求
- const controller = new AbortController();
-
- const CancelToken = axios.CancelToken;
- const source = CancelToken.source();
-
- axios.get('/user/12345', {
- cancelToken: source.token,
- signal: controller.signal
- }).catch(function (thrown) {
- if (axios.isCancel(thrown)) {
- console.log('Request canceled', thrown.message);
- } else {
- // 处理错误
- }
- });
-
- axios.post('/user/12345', {
- name: 'new name'
- }, {
- cancelToken: source.token
- })
-
- // 取消请求 (message 参数是可选的)
- source.cancel('Operation canceled by the user.');
- // 或
- controller.abort(); // 不支持 message 参数
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。