JS 없이도 form의 action/method/enctype로 POST 전송이
가능합니다.
method="post"에서 기본 enctype은 application/x-www-form-urlencoded입니다.
JS 객체를 그대로 axios.post(url, data)로 보내면, Axios가 보통 JSON으로 직렬화하여 전송하는 형태로 사용합니다.
// 예: POST JSON (객체를 그대로 전달)
const onClickPostRegisterJson = async () => {
try {
const titleValue = document.getElementById("title").value;
const contentsValue = document.getElementById("contents").value;
const data = { title: titleValue, contents: contentsValue };
await axios.post("http://localhost:8081/post/register1", data);
window.location.href = "./post_list.html";
} catch (error) {
console.log(error);
alert("예상치 못한 에러가 발생하였습니다.");
}
};
application/x-www-form-urlencoded 형식은 URLSearchParams로 key/value를 구성해서 보내는
방식이 대표적입니다.
// 예: x-www-form-urlencoded (URLSearchParams)
const onClickPostRegisterUrlencoded = async () => {
try {
const titleValue = document.getElementById("title2").value;
const contentsValue = document.getElementById("contents2").value;
const params = new URLSearchParams();
params.append("title", titleValue);
params.append("contents", contentsValue);
await axios.post("http://localhost:8081/post/register2", params, {
headers: { "Content-Type": "application/x-www-form-urlencoded" }
});
window.location.href = "./post_list.html";
} catch (error) {
console.log(error);
alert("예상치 못한 에러가 발생하였습니다.");
}
};
파일 업로드/멀티파트 전송이 필요하면 FormData를 만들어 append()로 넣고 POST로 보냅니다.
// 예: multipart/form-data (FormData)
const onClickPostRegisterFormData = async () => {
try {
const titleValue = document.getElementById("title3").value;
const contentsValue = document.getElementById("contents3").value;
const formData = new FormData();
formData.append("title", titleValue);
formData.append("contents", contentsValue);
// 일반적으로 FormData를 바디로 넘기면 멀티파트로 전송하는 형태로 사용합니다.
await axios.post("http://localhost:8081/post/register3", formData);
window.location.href = "./post_list.html";
} catch (error) {
console.log(error);
alert("예상치 못한 에러가 발생하였습니다.");
}
};
data.append("title", title)처럼 변수명이 잘못 들어가면 값이 전송되지 않습니다(여기서는
titleValue/contentsValue로 수정).