POST api 요청을 하던 중 아래와 같은 에러가 발생했다.

구글링을 하니 "Content-Type": "application/json"으로 하지 않아서 발생하는 에러라고 했다. 그렇지만 이렇게 바꿔도 에러는 계속 발생했다.

포스트맨에 요청했을 때도 415 Unsupported Media Type을 마주했다. 에러 메세지를 보니
The request entity has a media type which ther server or resource does not support. For example, the client uploads an image as image/svg+xml but the server requires that images use a different format.
이렇게 나와 있어서 뭔가 Content-Type의 문제 같다고 생각했다. 그래서 백엔드 코드를 찾아봤는데 Content-Type이 "multipart/form-data" 였다...!!! 그래서 바꾸고 다시 시도했더니 성공했다^ㅇ^
그리고 form-data 양식에 맞춰서 request를 해야 했다. 여기서는 request, file 맞춰줘야 했다. file에는 input type을 file로 지정하고 받아와서 이를 넣어줬다.
try {
const formData = new FormData();
formData.append('request', JSON.stringify({
title: postData.title,
content: postData.content,
category: postData.category,
postType: postData.postType,
postVoteType: postData.postVoteType,
pollTitle: postData.pollTitle,
multipleChoice: postData.multipleChoice,
parent_id: postData.parent_id,
deadline: postData.deadline,
point: postData.point,
}));
formData.append('file', file);
const response = await axios.post(`${baseUrl}/posts/`, formData, {
headers: {
atk : authToken,
"Content-Type": "multipart/form-data",
},
});
console.log('Post 요청 성공:', response.data);
} catch (error) {
console.error('Post 요청 실패:', error);
}
};
너무 막힐 때는 백엔드 코드를 뜯어보는 것도 괜찮은 방법 같다.