이때까지 게시물 작성(Create), 게시물 보여주고 읽기(Read)까지 끝냈고 Update, Delete가 남았다. 오늘은 편집을해서 그 데이터들을 넘겨주고 그걸 db에 update하는 기능을 구현했다.
그런데 먼저 프로젝트에서 게시판 편집 조건중에 비밀번호를 확인하고 편집 가능여부를 클라이언트에 제공하게 해야한다고 하여 Create에 다시 돌아가서 비밀번호 작성란을 넣고 서버쪽 Create api에 password를 넣어줬다.(+작성자까지)
router.post("/posts", async (req, res) => {
const { title, subtitle, context, category, date, writer, password } =
req.body;
await Posts.create({
title,
subtitle,
context,
category,
date,
writer, //작성된 게시물에 작성자와 비밀번호를 DB에 추가
password,
});
}
res.send({ result: "success" });
});
물론 포스트 모델에 Schema도 추가해주고,
writer: {
type: String,
required: true
},
password: {
type: String,
required: true
},
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const postId = urlParams.get("postId");
$(document).ready(function() {
readPost();
});
일단 어떤 포스트를 클라이언트가 클릭했는지 url에있는 postId로 db에 있는 데이터들이랑 편집해주고 다큐먼트가 켜질때 function readPost();
function readPost() {
$.ajax({
type: "GET",
url: `/api/posts/${postId}`,
data: {},
success: function(response) {
let postsDetail = response["detail"]; //db에서 받아온 데이터 미리 input칸에
$("#webTitle").text(postsDetail["title"]); //뿌려주는 작업들
$('#title').val(postsDetail['title']);
$('#subtitle').val(postsDetail['subtitle']);
$('#category').val(postsDetail['category']);
$("#context").text(postsDetail["context"]);
$("#writer").val(postsDetail["writer"]);
}
}
})
}
다 뿌려주고 난뒤 클라이언트가 직접 다시 입력한 값들을 적고 "저장" 버튼클릭하면
function editPasswordCheck(){
$.ajax({
type: "GET",
url: `/api/posts/${postId}`,
data: {},
success: function(response) {
let postsDetail = response["detail"];
if($("#password").val() !== postsDetail['password']){
alert("패스워드가 일치하지 않습니다.")
}else{
editPost();
}
}
})
}
하고 다시 생각해보니 백쪽에서 불러온 패스워드와 클라이언트가 친 패스워드를 프론트에서 비교하는게 과연 보안적으로 좋은방식인가라는 생각이 들었다. 보안적으로 많이 취약해 보인거같다는 생각이들었다. 다음 프로젝트에서는 백쪽에서 비교하고 에러메세지를 보내는쪽으로 해야겠다.
패스워드가 일치하면 editPost();
function editPost(){
title1 = $('#title').val()
subtitle1 = $('#subtitle').val()
category1 = $('#category').val()
context1 = $('#context').val()
writer1 = $('#writer').val()
$.ajax({
type: "PUT",
url: `api/posts/${postId}/edit`,
data: {
title = title1,
subtitle = subtitle1,
category = category1,
context = context1,
writer = writer1,
},
success: function(response) {
if (response["result"] == "success") {
alert("수정완료");
window.location.href= `/read?postId=${postId}`
}
}
})
}
delete 기능은 간단해서 내친김에 해버렸다.
function deletePasswordCheck(){
$.ajax({
type: "GET",
url: `/api/posts/${postId}`,
data: {},
success: function(response) {
let postsDetail = response["detail"];
if($("#password").val() !== postsDetail['password']){
alert("패스워드가 일치하지 않습니다.")
}else{
deletePost();
}
}
})
}
똑같이 비밀번호를 비교해주고
function deletePost(){
$.ajax({
type: "DELETE",
url: `/api/delete/${postId}`,
data: {},
success: function(response) {
if (response["result"] == "success") {
alert("삭제 완료")
window.location.href='/list'
}
}
})
}
현재 보고있는 postId와 같은 데이터를 찾아서 지워준다.
router.put("/posts/:postId/edit", async (req, res) => {
const { postId } = req.params;
const { title, subtitle, context, category, writer } = req.body;
await Posts.updateOne( //같은 postId 데이터를 req.body에 담아온 데이터로
{ _id: ObjectID(postId) }, // 업데이트
{ $set: { title, subtitle, context, category, writer } }
);
}
res.send({ result: "success" });
});
router.delete("/delete/:postId", async (req, res) => {
const { postId } = req.params;
posts = await Posts.findOne({ _id: ObjectID(postId) }); //같은 Id 포스트찾고
await Posts.deleteOne({ _id: ObjectID(postId) }); // 그걸 지워준다
res.send({ result: "success" });
});