Abortcontroller 및 Axios 취소 토큰의 실제 사용 사례
소개
API 요청과 관련된 기능을 구현할 때 기능 요구 사항에 따라 또는 애플리케이션에서 예기치 않은 동작을 방지하기 위해 보류 중인 요청을 취소해야 하는 경우가 있습니다.
이러한 경우 중 일부는 다음과 같습니다.
이와 같은 시나리오를 처리하기 위해 최신 브라우저에는 Fetch API 를 사용할 때 하나 이상의 API 요청을 취소할 수 있는 AbortController 인터페이스가 내장되어 있습니다.
Axios HTTP 클라이언트 패키지는 철회된 cancelable promises proposal 을 기반으로 하는 취소 토큰 API를 사용하여 API 요청 취소를 처리합니다.
목표
Fetch API 및 Axios 취소 토큰을 사용하여 API 요청을 취소하는 방법을 시연하기 위해 자동 완성 검색 기능을 구현할 것입니다.
자동완성 검색은 사용자가 검색창에 값을 입력할 때마다 API 요청을 합니다.
이 기능은 입력 내용이 변경될 때마다 새로운 요청을 만들기 전에 보류 중인 API 요청을 취소하는 방법을 보여줍니다.
구현 순서도:
구현을 진행하기 전에 검색 입력 필드를 만든 다음 이벤트 리스너와 리스너 콜백을 추가하겠습니다.
먼저 검색 입력 필드를 선택합니다.
const input = document.querySelector('#search');
그런 다음 검색 필드에 이벤트 리스너를 추가하고 입력 변경 시 호출되는 콜백
searchItems
을 추가합니다.input.addEventListener('input', searchItems);
searchItems
콜백 함수는 Fetch API 및 axios를 사용하여 구현되며, 각 줄에는 기능을 설명하기 위해 주석이 추가됩니다.가져오기 API 구현
API 요청을 하기 전에
AbortController()
생성자를 사용하여 컨트롤러를 만든 다음 AbortSignal
속성을 사용하여 연결된 AbortController.signal
개체에 대한 참조를 가져옵니다.가져오기 API 요청이 시작되면 요청 옵션 개체 내부의 옵션으로
AbortSignal
를 전달합니다. 이렇게 하면 신호 및 컨트롤러가 가져오기 요청과 연결되고 AbortController.abort()
를 호출하여 중단할 수 있습니다.abort()
메소드가 호출될 때 fetch()
약속은 DOMException
라는 AbortError
라는 이름으로 거부된다는 점에 유의하는 것이 중요합니다. DOMException
이름을 사용하여 요청 취소로 인해 오류가 발생했는지 알 수 있습니다.구현을 진행해 보겠습니다. 각 행에 주석을 달아 수행하는 작업을 설명합니다.
...
let controller;
function searchItems(event) {
// Grab the user input from the input event param
const query = event.target.value;
// Check if an AbortController instance has been assigned to the controller variable, then call the abort method when true.
// To cancel a pending request the abort() method is called.
if (controller) controller.abort();
// A new instance of the AbortController is created before making the API request
controller = new AbortController();
// grab a reference to its associated AbortSignal object using the AbortController.signal property
const signal = controller.signal;
// We pass in the AbortSignal as an option inside the request's options object
fetch(`https://example.com?name=${query}`, {signal})
.then(function(response) {
console.log(response);
}).catch(function(e) {
// Check the exception is was caused request cancellation
if (e.name === 'AbortError') {
// handle cancelation error
} else {
// handle other error
}
})
}
액시오스 구현
axios를 사용하여 진행 중인 요청을 취소하려면 메시지에 대한 선택적 매개 변수를 사용하는 취소 토큰 API의
cancel(...)
메서드가 호출됩니다.API 요청을 하기 전에 취소 토큰이 생성되어 axios 구성에 대한 옵션으로 전달됩니다. 토큰은 현재 요청과
cancel(...)
메서드를 연결합니다.취소로 인해 axios 약속이 거부되면 예외를 인수로 사용하는
axios.isCancel(...)
메서드를 사용하여 예외가 취소로 인한 것인지 확인합니다.구현을 진행해 봅시다. 각 줄은 주석 처리되어 무엇을 하는지 설명합니다.
...
// create a source variable which we will later assign cancel token using the CancelToken.source factory.
let source;
function searchItems(event) {
// Grab the user input from the input event param
const name = event.target.value;
// Check if a CancelToken.source has been assigned to the source variable, then call the cancel method when true.
if (source) source.cancel('Operation canceled by the user.');
// Assign the source factory to the source variable
source = axios.CancelToken.source();
const option = {
params: { name }, // Pass query strings via param option
cancelToken: source.token // add the cancel token, as an option for the request
};
axios.get('https://example.com', option)
.then((response) => {
console.log(response)
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
}
결론
이 자습서에서는 자동 완성 검색 기능을 구현하여 Fetch API 및 Axios 요청을 취소하는 방법을 배웠습니다. 이 구현을 통해 필요에 따라 요청 취소 기능을 생성할 수 있기를 바랍니다.
추가 리소스
AbortController - Web APIs | MDN
Reference
이 문제에 관하여(Abortcontroller 및 Axios 취소 토큰의 실제 사용 사례), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/03balogun/practical-use-case-of-the-abortcontroller-and-axios-cancel-token-4k61텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)