mongodb I Cant Delete Data from fetch in react [duplicate]

polkgigr  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(123)

此问题在此处已有答案

I Cant Delete Data from database using fetch and express in react(2个答案)
20天前关闭。
我有一个MERN应用,使用了Fetch API。我想在点击时删除特定数据。
每当我点击删除它显示'无法删除。'

状态为404:未找到

这里是我的前端代码请帮助我与此

我尝试过的:

import {useState,useEffect} from 'react';
import './App.css';

function App() {

  const userArr = [
    {}
  ]

 const [form, setForm] = useState(userArr);
 const [users,setUsers] = useState([]);
 
 const [sid,setId] = useState("");
 const [fname, setFName] = useState("");
 const [pass,setPass] = useState("");



 const handleName = (e) =>{
    setFName(e.target.value);
  
   
 }

 const handlePass = (e) =>{
  setPass(e.target.value);
  console.log("pass is -->"+pass)
 }

 const handleForm = (e) =>{
  setId(Math.random()+1);
  setForm({
    ...form,
    userid: sid,
    username:fname,
    password:pass
  })
 }

 const removeElm = (userid) =>{

  fetch(`http://localhost:9090/demo/users/${userid}`, {
    method: "DELETE",
    headers: {
     'content-Type': 'application/json',
    },
  })
    .then(response => response.text())
    .then((err) => console.log(err))
    .then(() => {
      setUsers(values => {
        return values.filter(item => item.userid !== userid)
      })
      
 })

}

 const handleSubmit = async (e) =>{
  e.preventDefault();
  const response = await fetch("http://localhost:9090/demo",{
    method:'POST',
    body:JSON.stringify(form),
    headers:{
      'Content-Type':'application/json'
    }
  })

  const data = await response.json();
  console.log(form);
  console.log(response);
  console.log(data);
 }

 const getUsers = async () =>{
  const response = await fetch("http://localhost:9090/demo",{
    method:'GET',
  })

  const data = await response.json();
  setUsers(data);
 }
    
 useEffect(()=>{
  getUsers();
 },[])

  return (
    <div className="App">
     <div>
      <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username</label>
       <input type="text" name='username' onChange={handleName} />
       <label htmlFor="password">Password</label>
       <input type="text" name='password' onChange={handlePass} />
       <button onClick={handleForm}>Submit</button>
      </form>
     </div>
     <ul>
     {users.map(obj=><li key={obj.userid}> <span>Username:{obj.username}</span>, <span>Password:{obj.password}</span>  <button onClick={() => removeElm(obj._id)}>Remove</button> </li>
   )}
     </ul>
    </div>
  );
}

export default App;

字符串

后台

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

// mongo db
main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/demo');
  console.log('db connected');
}

// schema
const userSchema = new mongoose.Schema({
      userid: Number,
    username: String,
    password: String
  });

// model- class from schema
const UserModel= mongoose.model("User",userSchema);
console.log(UserModel) // to check if the Model has been created successfully or not

const server = express();
// middleware
server.use(cors());
server.use(bodyParser.json());

// API
//CRUD - Create
server.post('/demo',async (req,res)=>{
    let user = new UserModel();
    user.userid  = req.body.userid;
    user.username = req.body.username;
    user.password = req.body.password;
    // save function
    const savedDoc = await user.save();
    console.log(savedDoc);
    res.json(savedDoc);
})

//CRUD - Read
server.get('/demo',async (req,res)=>{
  const docs =  await UserModel.find({});
  console.log("All Docs=>"+docs);
  res.json(docs);
})

server.listen(9090,()=>{
    console.log(`Server is running on port 9090`);
})


我想在点击时删除特定数据。
请帮我拿这个。

bkhjykvo

bkhjykvo1#

试试这个:-
拆卸元件前端

const removeElm =  (id) =>{
  
    fetch(`http://localhost:8080/2ndapp/users/${id}`, {
      method: "DELETE",
      headers: {
       'content-Type': 'application/json',
      },
    })
      .then(response => response.text())
      .then((response) => console.log(response.status, response.statusText))
      .then(() => {
        setUsers(values => {
          return values.filter(item => item.id !== id)
        })
  })
  
   }

字符串

服务器端您添加此

server.delete("/demo/users/:id", async (req, res) => {
    try{
      const idToDelete = req.params.id;
      console.log("-->Its Running");
      const deletedDoc =await UserModel.findByIdAndDelete({"_id": new mongoose.Types.ObjectId(idToDelete)});
      console.log("Its Running2"); 
      return res.status(204).send('Deleted');
        }catch(err){
        new Error(err);
      };
  });


你应该使用mongo提供的Object ID。

相关问题