JSON "Unexpected token '<'" 오류: 서버가 HTML을 보냈을 때
0번 위치의 Unexpected token <는 JSON이 아니라 HTML을 받았다는 뜻입니다. 404, 500, 로그인 페이지 같은 흔한 원인과 디버깅 방법입니다.
실제로 보이는 오류 메시지
| Chrome · Edge · Node.js | SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON |
|---|---|
| 예전 Chrome · Node.js 18 이하 | SyntaxError: Unexpected token < in JSON at position 0 |
| Python json.loads | json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) |
| 이 도구 | 줄 1, 열 1: 값이 필요한데 '<'이(가) 있습니다 |
원인
텍스트가 <로 시작하니 JSON이 아니라 HTML입니다. 서버가 오류 페이지(404, 500)나 로그인·리다이렉트 페이지를 보냈거나, API 주소가 틀려서 개발 서버의 index.html이 왔을 가능성이 큽니다.
잘못된 예
<!DOCTYPE html> <html> <head><title>404 Not Found</title></head> </html>
해결 방법
res.json()을 부르기 전에 res.ok와 Content-Type을 확인하고, await res.text()로 실제로 받은 내용을 찍어 보세요. 그다음 URL, 프록시 설정, 서버 오류를 고치면 됩니다.
고친 예
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
console.log(res.headers.get('content-type'));
const data = await res.json();