Web
[HTML, JS] form을 이용한 데이터 POST 요청 시 Not Found 404 오류
hyzzzy
2023. 5. 29. 16:18
✏️ 문제 상황
회원정보를 수정하는 버튼을 클릭하면 NOT FOUND 404 에러 페이지로 이동하게 된다.
🧐 문제 원인
서버에서는 에러가 없다고 하셨는데 분명 올바른 url로 post 요청을 보냈으나 404 에러를 보게 되었다. 알고보니 form을 전송할 서버 쪽 스크립트 파일을 지정하는 action 속성을 따로 지정하는 걸 누락했다.
평소에 form 하나에 submit type 하나만 지정하게 되니 action 속성을 추가하는 게 익숙치 않았다..
/user-mypage/user-mypage.js
const isAllValid = checkValid();
if (isAllValid && confirm("회원 정보를 수정 하시겠습니까?")) {
try {
const response = await fetch("/update", {
method: "POST",
...
});
...
}
}
}
/user-mypage/user-mypage.html
<form class="user-form-box" method="post">
...
<input type="button" class="user-update" id="submitButton" value="수정"/>
<input type="button" class="user-delete" id="deleteButton" value="회원 탈퇴"/>
</form>
app.js
app.use("/", usersRouter);
routes/userRouters.js
//사용자 정보 업데이트
router.post("/update", checkSession, updateUserValidator, updateUserInfo);
//사용자 정보 삭제
router.delete("/user", checkSession, deleteUserByEmail);
😊 해결 방안
action 속성값을 js 코드에서 지정해주었다. 특히 하나의 form 안에서 여러 submit을 보낼 경우 혹은 button 여러 개로 다른 요청을 보낼 경우에 action 속성 값을 다르게 지정해서 데이터를 보낼 수 있다.
async function updateUser(event) {
if (isAllValid && confirm("회원 정보를 수정 하시겠습니까?")) {
document.querySelector('.user-form-box').action = '/update';
...
}
}
async function deleteUser(event) {
if (isAllValid && confirm("정말 탈퇴하시겠습니까?")) {
document.querySelector('.user-form-box').action = '/user';
...
}
}