• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Next.js 게시판 댓글기능 응용 삭제

댓글기능 응용 삭제

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #103312

    김수현
    참가자
    오늘 열공중이라 선생님을 귀찮게 해드리네요^^;;;
    댓글 삭제 기능을 만들고 있는데요. 실행하니까 아래와 같은 오류가 발생하고 삭제는 되지 않네요.
    스크린샷 2023-11-07 161233
    이것도 클라이언트와 서버 코드에서 각각 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('로그인 후 본인 글만 삭제가능')
            }
        }
    }
    #103324

    codingapple
    키 마스터
    서버에서 else문 실행되는 것일 뿐인거같은데
    서버에서 왜 else문 실행되나 확인해봅시다
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠