MERN 應用程式無法從 MongoDB 中刪除項目
P粉427877676
P粉427877676 2024-04-01 16:25:59
0
1
334

我有一些查詢要從 mongo 中刪除項目:

deleteCustomer: build.mutation({
        query: (id) => ({
            url: `client/cutomers/${id}`,
            method: 'DELETE',
            body: 'id',
        }),
        providesTags: ['DeleteUser'],
    }),

它在控制器中的外觀:

export const deleteCustomer = async (req, res) => {
    try {
        const { id } = req.params;
        const formattedUsers = User.findByIdAndDelete(id);
        res.status(200).json(formattedUsers);
    } catch (e) {
        res.status(404).json({ message: e.message })
    }
}

路線如何:

import express from "express";
import { getEmployees, getCustomers, getTransactions, getGeography, deleteCustomer, getCustomer } from "../controllers/client.js";

const router = express.Router();

router.get("/employees", getEmployees);
router.get("/customers", getCustomers);
router.get("/transactions", getTransactions);
router.get("/geography", getGeography);

router.get("/customers/:id", getCustomer);
router.delete("/customers/:id", deleteCustomer);

export default router;

一旦我要求從 byza 中刪除對象,我就會收到以下錯誤:

我已經驗證使用 fetch 時獲取請求可以正常工作。 這就是我提出請求的方式:

const [deleteCustomer] = useDeleteCustomerMutation()   

function handleDeleteUser(id) {
    // fetch('http://localhost:5001/client/customers/' + id, {
    //     method: 'GET',
        // })
        // .then(res => res.json())
        // .then(res => console.log(res))
        deleteCustomer(id)
    }

我相信我沒有在控制器層級正確實作deleteUser中的刪除功能。我非常感謝您關於解決此問題的建議:)

P粉427877676
P粉427877676

全部回覆(1)
P粉924915787

查看您正在取得的路由 URL。在您的螢幕截圖上,您目前發出的發布請求網址似乎是 http://localhost:5001/client/cutomers/...

我認為它在以下函數中:

deleteCustomer: build.mutation({
        query: (id) => ({
            url: `client/cutomers/${id}`, // You put cutomers instead of customers
            method: 'DELETE',
            body: 'id',
        }),
        providesTags: ['DeleteUser'],
    }),

這可以解釋為什麼你的伺服器給出 404 not found 回應。

您可以嘗試進行更正並向我們提供更新嗎?

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!