Request with GET/HEAD method cannot have body 오류 해결 방법

반응형

오류

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

 

fetch("https://jsonplaceholder.typicode.com/posts", {
  body: JSON.stringify({id: 1})
}).then(function(response) {
   return response.json();
})

 

자바스크립트에서 fetch 호출 시 위와 같은 에러가 발생하였습니다.

원인

GET 방식의 호출인데, body에 값을 넣어서 발생하였습니다.

GET 방식은 읽기 전용이기 때문에 body 값을 가질 수가 없습니다.

해결방법

1. 읽기 전용이 아닌 호출이면 GET방식이 아닌 POST 방식으로 변경합니다.

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST"
  body: JSON.stringify({id: 1})
}).then(function(response) {
   return response.json();
})

2. 읽기 전용 API이라면 id 값 URL 뒤에 붙여주는 쿼리 스트링 방식으로 변경합니다.

fetch("https://jsonplaceholder.typicode.com/posts/1", {
}).then(function(response) {
   return response.json();
})
728x90
반응형