서버로 구현한 게시글 수정하기 기능을 수정하기 버튼을 눌러서 프론트엔드에서 구현하고자 한다.
백엔드 단 코드
router 파일
// 게시글 수정 라우터
router.put('/:id', isAuth, defaultValidate.updatePost, postController.update);
controller 파일
module.exports = {
update: async (req, res, next) => {
const { id } = req.params;
const foundUser = res.locals.foundUser;
const { content } = req.body;
const foundPost = await Post.findOne({ where: { id } });
try {
if (foundUser.id !== foundPost.userId) {
return res.status(401).json({ Message: '수정할 권한이 없습니다.' });
}
await Post.update(
{ content },
{
where: { id },
}
);
return res.status(200).json({ message: '게시글을 수정하였습니다.' });
} catch (err) {
console.log(err);
res.status(400).json({ errorMessage: '게시글 수정에 실패하였습니다.' });
}
},
}
validation 파일
const defaultValidate = {
updatePost: [
body('content')
.trim()
.notEmpty()
.withMessage('수정할 내용을 입력해주세요.')
.isLength({ min: 10 })
.withMessage('수정할 내용은 10자 이상을 입력하셔야 합니다.'),
validate,
],
}
html 파일 중 수정하는 버튼 부분
<button class="btn btn-dark" type="button" onclick="postUpdate()">
수정하기
</button>
마지막으로 이번에 구현한 script파일이다.
// 게시글 수정
async function postUpdate() {
const obj = {};
const id = new URL(location.href).searchParams.get('id');
const updateContent = prompt('수정할 내용을 입력하세요');
obj.content = updateContent;
const option = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: localStorage.getItem('Authorization'),
},
body: JSON.stringify({obj}),
};
try {
const fetchedData = await fetch(
`http://localhost:3030/posts/${id}`,
option
).then((d) => {
return d.json();
});
window.location.reload();
} catch (e) {
console.error(e);
}
}
문제 발생: 계속해서 빈 문자열이 전달되는 에러가 발생
문제 해결:
1) id 확인하기 console.log('id')
=> 세부페이지에서 id가 잘 확인이 되었다.
2) updateContent 확인하기
=> 프롬프트에 적힌 내용물이 제대로 전달이 되는지 확인 obj.content밑에 console.log(updateContent) => 확인 결과 입력한 데이터는 개발자 도구의 network의 payload에도 잘 찍혔다.
3) fetch로 put을 보내는 방식이 잘 되었는지 확인하기 => return d.sjon()후 나와서 console.log(d)를 찍어보았더니 에러가 떴다.
그렇다면 보내주는 과정에서 무언가 문제가 있다는 것이다.
확인해보니 JSON.stringify({obj}) 에서 문제가 있었다.
const obj ={} 객체이고 객체인 obj를 또 중괄호로 묶어주니 그 안에있는 문자열을 해석하지 못해서 일어난 일이다.
따라서 저부분을
JSON.stringify(obj)
중괄호를 빼주고 실행하면 된다.