无法实现拦截器以在超时的情况下取消axios请求

时间:2019-04-23 14:36:47

标签: javascript axios interceptor

在我的Nestjs应用中,我正在使用Axios调用。我试图将令牌附加到每个axios请求,并且只有在发生超时错误时,我才希望它取消令牌,记录错误并停止该请求。当前使用此代码,拦截器可以正常工作,但每次都会执行if(Axios.isCancel(error)){}块。 即使没有超时,我也会收到有效的响应。 如果没有超时,我不想取消令牌。

当前,无论超时与否,我收到的每个请求!

======Request canceled=== Cancel { message: 'Operation canceled due to timeout!' }

import { Injectable, NestInterceptor, CallHandler, HttpCode } from '@nestjs/common';
import { Observable } from 'rxjs';

import Axios from 'axios';
import { request } from 'https';
import { timeout } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {

  intercept(context: any, next: CallHandler): Observable<any> {

    const CancelToken = Axios.CancelToken;
    const source = CancelToken.source();

    const url:string = context.url? context.url: context.args[0].url;

    Axios.defaults.timeout = 2000;
    Axios.get(url, {
      cancelToken: source.token
    }).then( (res)=> {
      console.log(res,'');
    }, error => {
        throw new Axios.Cancel('Operation canceled due to timeout!');
    }
    ).catch( (error)=> {
       if (Axios.isCancel(error)) {
         console.log('=====================Request canceled=======', error);
       } else {
         // catchError(error => throwError(new Error('Service Timed out!')))
         console.log('--else part------------------------------------');
       }
     });
    return next.handle();
  }
}

1 个答案:

答案 0 :(得分:0)

我相信问题是您在请求期间总是因任何错误而抛出Axios.Cancel。也许应该在promise错误处理程序中而不是在catch块中检查它,如下所示:

Axios.get(url, {
  cancelToken: source.token
}).then( (res)=> {
  console.log(res,'');
}, (error) => {
  if (Axios.isCancel(error)) {
    throw new Axios.Cancel('Operation canceled due to timeout!');
  } else {
    console.log('IT IS NOT a timout error.');
  }       
}
).catch( (error)=> {
   console.log('Error during token cancelation');
});