mongoose 使用Axios.delete()向后端传递要删除的项目的ID数组时出错

frebpwbc  于 10个月前  发布在  Go
关注(0)|答案(1)|浏览(151)

我正在尝试从数据库中删除几个项目(mongoose)通过选择它们并单击删除按钮。我已经设法从数据库中获取列表中每个元素的ID。我正在收集列表中所选项目的ID并将其存储在名为isCHecked的数组中,但问题是当我单击立即删除它们时,我得到一个AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST'错误。我觉得ID没有有效地传递到后端,请问我哪里弄错了?
这里只是代码片段。谢谢

const StockItems = () => {
    const [stockItemsList, setStockItemsList] = useState([])
    const [showCheckBox, setShowCheckBox] = useState(false)
    const [isCHecked, setIsChecked] = useState([])

    const handlecheckbox=(e)=>{
        const {value, checked} = e.target
        console.log(value)
        if(checked){
           setIsChecked([...isCHecked, value])
        }else
          setIsChecked(isCHecked.filter((e)=> e!==value))

    }

    const deleteAll = async()=>{
        console.log(isCHecked)
         await Axios.delete('http://localhost:3500/newItems', {isCHecked}).then((response) => {
            console.log(response.status)
            console.log(response.data)
        })
        .catch((e) => console.log('something went wrong :(', e));
        //setDeleteMessage(response.data.deleteMessage)
    }
}

//controller code (Backend)
const NewItemsData = require('../models/NewItemsData')
const asyncHandler = require('express-async-handler')

const deleteNewItems = asyncHandler(async (req, res) => { 
    const id = req.body
    console.log(id) // this shows undefined in the console

    if(!id) {
       return res.status(400).json({message: 'Items Id is required'})
    }
    const items = await NewItemsData.findById({_id: {$in: id}}).exec()

    if(!items){
       return res.status(400).json({message: 'Items does not exist'})
    }

     await items.deleteMany()
   // const reply = `Username ${result.username} with ID ${result._id} deleted`
    res.json({message: 'Items has been deleted'})
})

module.exports = {
    deleteNewItems,  
}

//Server
app.use('/newItems', require('./routes/newItemsRoutes'))// a line just to show how my route is mounted in the server

//Routes
const express = require('express')
const router = express.Router()
const newItemsController = require('../contollers/newItemsController')

router.route('/')
      .get(newItemsController.getAllNewItems)
      .post(newItemsController.createNewItems)
      .patch(newItemsController.updateNewItems)
      .delete(newItemsController.deleteNewItems)

字符串

yi0zb3m4

yi0zb3m41#

在你的前端,你需要在请求体中正确地传递ID数组。而不是{ isCHecked },你应该传递一个带有{ ids: isCHecked }这样的键的对象。最好使用data,而不是直接发送对象。

const deleteAll = async () => {
    console.log(isCHecked);
    await Axios.delete('http://localhost:3500/newItems', { data: { ids: isCHecked } })
        .then((response) => {
            console.log(response.status);
            console.log(response.data);
        })
        .catch((e) => console.log('something went wrong :(', e));
};

字符串
您需要从请求体中正确检索服务器中的ID。您正在尝试访问req.body,但您应该访问req.body.ids

const deleteNewItems = asyncHandler(async (req, res) => {
    const ids = req.body.ids; // Change this line
    console.log(ids);

    if (!ids || ids.length === 0) {
        return res.status(400).json({ message: 'Items Id is required' });
    }

    const items = await NewItemsData.findById({ _id: { $in: ids } }).exec();

    if (!items) {
        return res.status(400).json({ message: 'Items do not exist' });
    }

    await items.deleteMany();
    res.json({ message: 'Items have been deleted' });
});

相关问题