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

home2 게시판 Next.js 게시판 next.js에서 삭제기능 시 오류

next.js에서 삭제기능 시 오류

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

    양정민
    참가자
    //listserver.js
    import { MongoClient } from 'mongodb';
    const uri = "mongodb+srv://harinworld95:@cluster0.yl5buva.mongodb.net/?retryWrites=true&w=majority";
    const client = new MongoClient(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    });
    export default async function handler(req, res) {
    try {
    await client.connect();
    const database = client.db('node-todoapp');
    const collection = database.collection('post');
     
    if (req.method === 'DELETE') {
    const id = req.query.id;
    const result = await collection.deleteOne({ _id: new ObjectId(id) });
    console.log(result.deletedCount + ' document(s) deleted');
    return res.status(204).end();
    } else {
    const posts = await collection.find({}).toArray();
    return res.status(200).json(posts);
    }
    } catch (error) {
    console.log(error);
    res.status(500).json({ message: 'Server Error' });
    } finally {
    await client.close();
    }
    }
    
    // List.js
    
    import React, { useEffect, useState } from 'react'
    import styles from '../../styles/list.module.scss'
    const List = () => {
    const [posts, setPosts] = useState([]);
    useEffect(() => {
    async function fetchData() {
    const res = await fetch('/api/listserver');
    const data = await res.json();
    setPosts(data);
    }
    fetchData();
    }, []);
    const handleDelete = async (id) => {
    const res = await fetch(`/api/listserver/${id}`, {
    method: 'DELETE',
    });
    if (res.ok) {
    // convert the id to an ObjectId before filtering
    const deletedId = new ObjectId(id);
    // remove the deleted item from the state
    setPosts(posts.filter(post => post._id.toString() !== deletedId.toString()));
    } else {
    console.log('Failed to delete item');
    }
    };
    return (
    <div className={styles.list}>
    <h3>DB에서 가져온 todo 리스트</h3>
    {posts.map((post) => (
    <div className={styles.listbox} key={post._id}>
    <p>글번호 : {post._id}</p>
    <p>할일 제목 : {post.제목}</p>
    <p>할일 마감날짜 : {post.날짜}</p>
    <button onClick={() => handleDelete(post._id)}>삭제</button>
    </div>
     ))}
    </div>
     )
    }
    export default List
    
    쓴글 db등록, list페이지에 출력까지 성공하였는데 삭제 기능이 작동을 안합니다.! 어떻게 해야하나요..??ㅠㅠ
     
    #82062

    codingapple
    키 마스터
    delete말고 post요청 써봅시다
    #82464

    양정민
    참가자
    말씀주신대로 post 요청을 사용하였는데도 삭제가 되지 않는데, 혹시
    const res = await fetch(`/api/listserver/${id}`, {
    method: 'POST',
    });
    
    `/api/listserver/${id}` fetch 경로가 잘못된건가요??
    #82488

    codingapple
    키 마스터
    서버도 if (req.method === 'DELETE') { 이거 POST로 바꿨나 확인해봅시다
    #82523

    양정민
    참가자
    네 확인하였습니다!
    http://localhost:3000/api/listserver/8 404 (Not Found)
    이런 오류가 뜨고 삭제 기능이 실행이되지 않습니다.!
    #82655

    codingapple
    키 마스터
    404는 서버파일 안만들어놨다는거라 위 URL로 요청하고 싶으면 
    /api/listserver/[어쩌구].js 만들어서 안에 서버기능 개발합시다
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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