sourcecode

경로 변경 시 모든 Axios 요청 중단 vue-router 사용

copyscript 2023. 8. 17. 21:47
반응형

경로 변경 시 모든 Axios 요청 중단 vue-router 사용

경로를 변경할 때 완료되기 전에 어떻게 Axios 요청을 중단/취소할 수 있습니까? vue-router.

사용자가 페이지를 열면 자동으로 액시오스 요청을 보내 데이터를 가져오지만, 사용자는 응답을 기다리지 않고 vue-router로 경로를 변경합니다. 액시오스 요청이 많을 것입니다.

그래서 내 문제에 대한 해결책이 있습니까?

업데이트: Axios(0.22.0+)

CancelToken이제 더 이상 사용되지 않습니다.다음을 사용하여 업데이트된 솔루션에 대한 @m0r 답변 확인AbortController다음은 공식 문서의 링크입니다.

https://axios-http.com/docs/cancellation

원답

기본적으로 글로벌 취소 토큰을 생성해야 합니다.

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

구성 매개 변수에 전달하여 모든 요청에 사용합니다.

GET 요청:

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

POST 요청:

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

그런 다음, vue-router 내에서beforeEach내비게이션 가드 다음을 사용하여 모든 요청을 취소할 수 있습니다.

source.cancel('Operation canceled by the user.');

취소를 위한 공식적인 공리 가이드는 다음과 같습니다: https://github.com/axios/axios#cancellation .

@fabrluex의 대답은 정확합니다.저는 여기에 API 호출이 많으면 각 api 호출 구성에서 취소 토큰을 전달해야 한다는 것을 추가하고 싶습니다.이 코드를 줄이기 위해 액시오스 인스턴스를 만들고 요청 가로채기를 추가하여 공통 취소 토큰을 추가한 다음 취소가 완료되거나 경로가 변경되면 토큰에 새 값을 할당할 수 있습니다.

// Some global common cancel token source

let cancelSource = axios.CancelToken.source();

// Request interceptor

export const requestInterceptor = config => {
  config.cancelToken = cancelSource.token;
  return config;
};

// Add request interceptor like this
const request = axios.create({ baseURL: SOME_URL });
request.interceptors.request.use(requestInterceptor);


// Now you can use this axios instance like this

await request.get('/users');

// and

await request.post('/users', data);

// When you will cancel
cancelSource.cancel('Your cancellation message');

// And all the api calls initiated by axios instance which has request interceptor will be cancelled.

편집하여 @Sunet Jain에 답합니다.

클래스를 만들고 업데이트할 수 있는 인스턴스를 만들 수 있습니다.

class CancelToken {
  constructor(initialValue) {
    this.source = initialValue;
  }
  getSource() {
    return this.source;
  }
  setSource(value) {
    this.source = value;
  }
  cancel() {
    this.source.cancel();
  }
}
export const cancelSource = new CancelToken(axios.CancelToken.source());

해당 인스턴스를 가져올 수 있습니다.cancelSource그리고 필요할 때 취소를 호출할 수 있습니다. 예를 들어 로그아웃할 때 취소 토큰이 제공된 모든 요청을 취소하기 위해 전화할 수 있습니다.cancelSource.getSource()

로그아웃 후

cancelSource.cancel('Cancelled');

그리고 사용자가 다시 로그인하면 이 글로벌 인스턴스에 새 취소 토큰을 설정합니다.

cancelSource.setSource(axios).CancelToken.source();

2022 업데이트 | Axios (0.22.0+)


CancelToken은 더 이상 사용되지 않습니다.이제 새 프로젝트에서 컨트롤러 중단을 사용해야 합니다.구현이 더 깔끔합니다.

const controller = new AbortController();

config 매개 변수로 컨트롤러 전달:

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});

요청을 취소하려면 다음을 사용하십시오.

controller.abort()

출처 : https://github.com/axios/axios#cancellation

언급URL : https://stackoverflow.com/questions/51439338/abort-all-axios-requests-when-change-route-use-vue-router

반응형