Trouble Shooting
[JavaScript] Error: Multipart: Boundary not found(feat. Fetch API)
dev_seon
2023. 7. 1. 12:16
1. 에러 발생
이미지 파일 전송을 위해 fetch() 메서드를 활용하여 다음의 코드를 작성했습니다.
const formData = new FormData();
formData.append('file', imageState.imageFile);
formData.append('name', imageState.imageName);
await fetch('/api/image', {
method: 'POST',
body: formData,
headers: {
'Content-type': 'multipart/form-data',
},
}).then((res) => res.json());
코드 작성 후 이미지 파일 전송 테스트를 하던 중 아래와 같은 에러가 발생했습니다.
Error: Multipart: Boundary not found
에러 내용을 확인해보니 멀티파트 바운더리를 찾을 수 없다는 내용이였습니다.
여기서 말하는 boundary는 multipart/form-data의 key/value 쌍을 구분짓기 위해 사용되며, multipart 엔티티의 Content-Type 필드에 필요한 파라미터입니다.
그런데, 위 코드와 같이 Fetch API로 multipart/form-data 유형을 POST 할 때 수동으로 Content-Type을 multipart/form-data로 지정하게 되면 브라우저가 boundary를 설정할 수 없게 된다는 것을 MDN 문서 내용을 통해 확인할 수 있었습니다.
Warning: When using FormData to submit POST requests using XMLHttpRequest or the Fetch API with the multipart/form-data content type (e.g. when uploading files and blobs to the server), do not explicitly set the Content-Type header on the request. Doing so will prevent the browser from being able to set the Content-Type header with the boundary expression it will use to delimit form fields in the request body.
2. 문제 해결
에러의 원인을 확인한 후 위 코드에서 Content-Type을 명시한 코드를 삭제했고, 에러를 해결할 수 있었습니다.
const formData = new FormData();
formData.append('file', imageState.imageFile);
formData.append('name', imageState.imageName);
await fetch('/api/image', {
method: 'POST',
body: formData,
}).then((res) => res.json());
참고자료
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects
- https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data