6 글 보임 - 1 에서 6 까지 (총 6 중에서)
-
글쓴이글
-
2023년 5월 9일 17:40 #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페이지에 출력까지 성공하였는데 삭제 기능이 작동을 안합니다.! 어떻게 해야하나요..??ㅠㅠ
2023년 5월 10일 18:51 #82464
양정민참가자말씀주신대로 post 요청을 사용하였는데도 삭제가 되지 않는데, 혹시 const res = await fetch(`/api/listserver/${id}`, { method: 'POST', }); `/api/listserver/${id}` fetch 경로가 잘못된건가요??
2023년 5월 10일 20:53 #82523
양정민참가자네 확인하였습니다! http://localhost:3000/api/listserver/8 404 (Not Found) 이런 오류가 뜨고 삭제 기능이 실행이되지 않습니다.!
2023년 5월 11일 09:37 #82655
codingapple키 마스터404는 서버파일 안만들어놨다는거라 위 URL로 요청하고 싶으면 /api/listserver/[어쩌구].js 만들어서 안에 서버기능 개발합시다
-
글쓴이글
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
- 답변은 로그인 후 가능합니다.