Fetch API로 POST 수행시, body 값이 null로 입력되는 에러
발생 에러
Fetch API로 POST를 수행 시, body 안의 title이 특정 문자로 설정해서 POST 했음에도, 실제 데이터의 title 값은 null인 에러가 발생했다.
async function postDocument() {
try {
const response = await fetch(API, {
method: 'POST', // POST
headers: {
},
body: JSON.stringify({
title: '새 파일',
}),
})
if (!response.ok) {
throw new Error('Network response was not ok!')
}
const data = await response.json()
console.log('성공: ', data)
} catch (error) {
console.error('실패: ', error)
}
}
postDocument();
---
성공: {"id": 1, "title": null}
이유
headers에 Content-Type 값을 설정해주지 않아서 발생하는 문제였다.
그래서 Content-Type에 application/json;을 할당했지만, 그래도 여전히 null로 입력되었다.
application/json뒤의 ;가 불필요하게 들어가 있어 발생하는 문제였다.
해결 방법
headers: {
'Content-Type': 'application/json', // title null로 들어가는 것 해결
},
'Content-Type' 값을 입력해주고, 그 값을 body에서 전달하려는 타입에 맞춰서 작성해준다. Content-Type 값으로 ;가 들어가지 않게 주의한다.
Leave a comment