2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2023년 11월 7일 16:26 #103312
김수현참가자오늘 열공중이라 선생님을 귀찮게 해드리네요^^;;; 댓글 삭제 기능을 만들고 있는데요. 실행하니까 아래와 같은 오류가 발생하고 삭제는 되지 않네요.
이것도 클라이언트와 서버 코드에서 각각 json 감싸고 풀고 해도 소용이 없네요. 어디가 잘못됐는지 확인 부탁드려요. Comment.js 클라이언트 쪽 코드입니다. ==========================
'use client' import { useEffect, useState } from "react";
export default function Comment(props) { let [comment, setComment] = useState('') let [data, setData] = useState([])
useEffect(() => { fetch('/api/comment/list?id=' + props._id) .then(r => r.json()) .then(result => { console.log(result) setData(result) }) }, []) return ( <div> <div>댓글목록보여줄부분</div> <hr /> {data.length > 0 ? data.map((a, i) => <p key={i}>{a.content}<span onClick={(e) => { fetch('/api/comment/delete', { method: 'DELETE', body: JSON.stringify(props._id) }) .then((r) => { return r.json() }) .then((result) => { console.log(result) }) }} >🗑️</span></p>
) : '댓글없음' } <input onChange={(e) => { setComment(e.target.value) }} /> <button onClick={() => { console.log(comment) fetch('/api/comment/new', { method: "POST", body: JSON.stringify({ comment: comment, _id: props._id }) }) .then(r => r.json()) .then(result => { setData([...data, result]) console.log(result)
}) }}>댓글전송</button> </div > ); } delete.js 서버쪽 코드입니다.
==========================
import { connectDB } from "@/util/database" import { ObjectId } from "mongodb" import { getServerSession } from "next-auth" import { authOptions } from "../auth/[...nextauth]"
export default async function handler(요청, 응답) {
if (요청.method == 'DELETE') {
let session = await getServerSession(요청, 응답, authOptions) console.log(요청.body) const db = (await connectDB).db('forum') let 찾은거 = await db.collection('comment').findOne({ _id: new ObjectId(요청.body) }) console.log(찾은거._id)
if (session) { if (찾은거.author == session.user.email) {
let result = await db.collection('comment').deleteOne({ _id: new ObjectId(요청.body) }) console.log(요청.body) return 응답.status(200).json('삭제완료') } else { return 응답.status(500).json('현재유저와 작성자 불일치') } } else { return 응답.status(500).json('로그인 후 본인 글만 삭제가능') }
}
}
-
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.