본문 바로가기
JavaScript

$.ajax() response 200이지만 error로 처리되는 문제

by lumayi 2022. 7. 1.

나의 상황

API를 호출하고 200을 받았는데 SUCCESS가 아닌 ERROR로 분류되어 처리되는 현상

원인

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

여기서 오류가 발생했는데, dataType의 형식이 ‘json’으로 되어있기 때문이었다.

contentType → request의 dataType

dataType → response의 dataType

이 차이를 제대로 알지 못하고 써서 생긴 문제였다.

저 API의 경우 response를 따로 반환하지 않는 API였는데, 비어 있는 response 데이터에 JSON을 적어버리니, 네트워크에서 내부적으로 json.parse 등의 처리가 제대로 되지 못해서 에러가 생겼다.

결국 success error는 statusCode만으로 분류되지 않는다.

위의 예처럼 데이터 파싱 과정에서도 200이지만 충분히 error를 뱉을 수 있음. 그 외에도 timeout, abort 에러도 있음.

해결방법

  1. ajax 코드 수정dataType에는 text, html, xml, script 등 다양한 타입이 들어올 수 있다.
  2. response 데이터가 없기에, 이 중 가장 순수한 데이터 타입인 text를 사용하여 해결.
  3. $.ajax({ type: 'POST', url: 'Jqueryoperation.aspx?Operation=DeleteRow', contentType: 'application/json; charset=utf-8', data: 'text', dataType: 'json', success: AjaxSucceeded, error: AjaxFailed });

 

반응형