티스토리 뷰

const fetchTemplate = function (requestUrl, method, header, body, ifSucceed) {
            return fetch(
                requestUrl, {
                method: method,
                headers: {},
                body: body
            }).then(response => {
                console.log(response)
                if (response.status === 200) {
                    return ifSucceed(response);
                }
                if (response.status === 400) {
                    errorHandler(response);
                }
            });
        };

이런식으로 자바스크립트에서 자주 사용되는 fetch API를 템플릿으로 빼서 개발하던 중에 일어난 이슈이다.

프론트에서 이미지나 동영상같은 파일을 첨부하면 fetch를 타고 서버로 전송하는 부분에서,
파일을 포함한 string 등 request 요소들을 FormData로 감싸서 던지고 있었다.

<form id="save-form" name="saveForm" enctype="multipart/form-data">
        <div class="form-group">
            <label for="hashtag">해시태그</label>
            <input type="text" name="hashtag" size="50" id="hashtag">
            <br>
            <label for="contents">내용</label>
            <input type="text" name="contents" id="contents"/>
            <br>
            <label for="file">파일 업로드</label>
            <input type="file" name="file" id="file">
            <br>
    </div>
    <button id="save-button" type="button">저장</button>
</form>

이때 fetch에서 headers 필드를 설정하려고 하면 제대로 동작하지않고, 아예 헤더를 설정하지않을때만 제대로 동작하는 이슈가 발생했다.

일반적으로 '파일과 FormData 전송'과 관련된 키워드로 구글에 검색하면
헤더를 'application/x-www-form-urlencoded'나 'multipart/form-data'로 설정하라는 글이 많이 나온다.
문제는 이렇게 설정해도 제대로 보내지지 않는다.

그래서 헤더에 ''같은 빈 문자열이나 null을 넣어보았지만 여전히 동작하지않는다.
{}으로 설정해보았더니 제대로 동작한다.

원인은 아래의 링크에서 알수있었다.
대충 fetch api로 formData를 보낼때 헤더를 설정하지말아야하고, 그 이유는 헤더에 자동으로 boundary라는 값이 붙기 때문이라고 한다.

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryIn@@@@@@@@@@@@

Uploading files using 'fetch' and 'FormData' · Muffin Ma

결론

Fetch API를 이용해 FormData를 보낼때,
헤더를 아예 설정하지않거나, {}로 설정해야한다.
'application/x-www-form-urlencoded'나 'multipart/form-data', "", null 등으로 설정시 제대로 동작하지 않는다.
그 이유는 boundary라는 값 때문.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함