본문 바로가기
Backend/Node.js

[ axios ] timeout이 제대로 작동하지 않을 때 요청 중단하는 방법

by aeong_ 2023. 2. 16.

오류발생


axios.get( URL, { timeout: 2000 } )		// 의도와 다르게 동작
	.then((res) => {
		console.log("SUCCESS");
	})
	.catch((err) => {
    	console.log("ERROR");
    })

  axios로 응답을 받고 응답 제한시간을 timeout을 통해 2초를 주었는데 2초가 지나도 계속 서버 응답을 기다리고 있다. 너 왜그래?

그래서 간단히 구글링 결과 stackoverflow에서 답을 찾을 수 있었다.

 

 

Timeout feature in the axios library is not working

I have set axios.defaults.timeout = 1000; I stopped the server that provides me with the APIs. But it takes more than 1s to timeout after sending a request. This is how my request looks: import...

stackoverflow.com

 

  그러니까, timeout 옵션은 응답을 기다리는 시간을 설정하는 방법으로, 지정된 시간 이후 응답이 없으면 요청이 실패 처리된다. 서버가 응답하는 데 오랜 시간이 걸리면 요청을 취소한다.

  하지만 IP주소나 도메인이 없는 등의 경우는 서버 연결 시간이 초과되는 것이므로 timeout이 작동하지 않는다.

이럴 때는 네트워크 요청을 중간에 중단할 수 있는 다른 방법을 사용해야 한다.

 

 

결론


 

Cancellation | Axios Docs

Cancellation Cancelling requests Setting the timeout property in an axios call handles response related timeouts. In some cases (e.g. network connection becomes unavailable) an axios call would benefit from cancelling the connection early. Without cancella

axios-http.com

공식문서에 따라 axios 호출을 직접 종료하려면 다음 방법이 있다. 

  - signal   

  - canceltoken

'canceltoken' 은 더이상 사용을 권장하지 않는다. (  axios v.0.22.0 이상부터 사용X )

canceltoken을 알아보고 싶으면 위 공식 문서 링크를 참고하자.

 

따라서 signal을 이용하여 요청을 중간에 중단한다.

signal & abortController는 Node.js 15+ 부터 가능하다 

function newAbortSignal(timeoutMs) {
  const abortController = new AbortController();
  setTimeout(() => abortController.abort(), timeoutMs || 0);
  
  return abortController.signal;
}

axios.get( URL, { signal: newAbortSignal(2000) })		
	.then((res) => {
		console.log("SUCCESS");
	})
	.catch((err) => {
		console.log("ERROR");
    })

 

Node.js 17.3 버전 이상을 사용하는 경우 다음의 API를 사용하여 더 간단하게 나타낼 수 있다.

axios.get( URL, {
   signal: AbortSignal.timeout(2000) 
}).then(function(res) {
   //...
});

 

이 방법으로도 요청 중단이 안된다면 axios 버전도 한번 확인하도록 해보자.

 

+ ChatGPT가 알려주는 timeout과 abortController의 차이점

그렇다고 한다.