-
fetch API POST 요청
-
아래,
fetch()
옵션 객체의 옵션들을 간략히 나열했는데.. 더 이상의 옵션 상세 설명은
MDN의 fetch() 전역함수
문서를 참조하시기 바랍니다..
[ fetch() 옵션 값들 ]
async function postData(url= "", data= {}) {
const response= await fetch(url, { // 옵션 기본 값은 *로 강조
method: "POST", // *GET, POST, PUT, DELETE 등
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
});
return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}
postData("https://example.com/answer", { answer: 42 }).then((data) => {
console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});
-
1.
fetch()
로 JSON 데이터 POST 요청하기:
async function postJSON(data) {
try {
const response= await fetch("https://example.com/profile", {
method: "POST", // 또는 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const result= await response.json();
console.log("성공:", result);
} catch (error) {
console.error("실패:", error);
}
}
const data= { username: "example" }
postJSON(data);
-
2.
fetch()
로 파일 업로드하기:
// 파일 업로드
async function upload(formData) {
try {
const response= await fetch("https://example.com/profile/avatar", {
method: "PUT",
body: formData,
});
const result= await response.json();
console.log("성공:", result);
} catch(error) {
console.error("실패:", error);
}
}
const formData= new FormData();
const fileField= document.querySelector('input[type="file"]');
formData.append("username", "abc123");
formData.append("avatar", fileField.files[0]);
upload(formData);
// 다수 파일 업로드
async function uploadMultiple(formData) {
try {
const response= await fetch("https://example.com/posts", {
method: "POST",
body: formData,
});
const result= await response.json();
console.log("성공:", result);
} catch(error) {
console.error("실패:", error);
}
}
const photos= document.querySelector('input[type="file"][multiple]');
const formData= new FormData();
formData.append("title", "My Vegas Vacation");
for(const [i, photo] of Array.from(photos.files).entries()) {
formData.append(`photos_${i}`, photo);
}
uploadMultiple(formData);