从数据库中删除产品和 table(mern 项目)

delete product from database and table (mern project)

从数据库中删除产品并 table(mern 项目) 这是我的代码。但产品未被删除并显示此错误 - xhr.js:210 DELETE http://localhost:3000/api/v1/admin/product/24e74a20a5e5e8574e231a0 404 (Not Found)

我正在尝试,但无法解决问题。请给我一些建议。

productRoute.js

router.route('/admin/product/:id')
.put(isAuthenticatedUser,authorizeRoles("admin"), updateProduct)
.post(isAuthenticatedUser,authorizeRoles("admin"), deleteProduct)

productController.js

exports.deleteProduct = catchAsyncError(async(req,res,next) => {
    const product = await Product.findById(req.params.id)

    if(!product){
        return next(new ErrorHandler("Product not found",404));
    }

    await product.remove();

    res.status(200).json({
        success:true,
        message:"product deleted successfully"
    })
})

productConstant.js

export const DELETE_PRODUCT_REQUEST = "DELETE_PRODUCT_REQUEST";
export const DELETE_PRODUCT_SUCCESS = "DELETE_PRODUCT_SUCCESS";
export const DELETE_PRODUCT_RESET = "DELETE_PRODUCT_RESET";
export const DELETE_PRODUCT_FAIL = "DELETE_PRODUCT_FAIL";

export const CLEAR_ERROR ="CLEAR_ERROR";

productAction.js

export const deleteProduct = (id) => async (dispatch) => {
  try {
    dispatch({ type: DELETE_PRODUCT_REQUEST });

    const { data } = await axios.delete(`/api/v1/admin/product/${id}`);

    dispatch({
      type: DELETE_PRODUCT_SUCCESS,
      payload: data.success,
    });
  } catch (error) {
    dispatch({
      type: DELETE_PRODUCT_FAIL,
      payload: error.response.data.message,
    });
  }
};

productReducer.js

export const productsReducer = (state ={products: []},action) => {
    switch(action.type){
        case ALL_PRODUCTS_REQUEST:
        case ADMIN_PRODUCT_REQUEST:
            return{
            loading:true,
            products:[]
            }
        case ALL_PRODUCTS_SUCCESS:
            return{
            loading:false,
            products:action.payload.products,
            productCount:action.payload.productCount
            }

        case ADMIN_PRODUCT_SUCCESS:
          return{
            loading:false,
            products:action.payload,
          }
        case ALL_PRODUCTS_FAIL:
        case ADMIN_PRODUCT_FAIL:
            return{
                loading:false,
                error:action.payload
            }
        case CLEAR_ERROR:
            return{
                ...state,
                error:null
            }
        default:
             return state;
    }
};

export const productReducer = (state = {}, action) => {
  switch (action.type) {
    case DELETE_PRODUCT_REQUEST:
      return {
        ...state,
        loading: true,
      };
    case DELETE_PRODUCT_SUCCESS:
      return {
        ...state,
        loading: false,
        isDeleted: action.payload,
      };

    case DELETE_PRODUCT_FAIL:
      return {
        ...state,
        loading: false,
        error: action.payload,
      };
    case DELETE_PRODUCT_RESET:
      return {
        ...state,
        isDeleted: false,
      };
    case CLEAR_ERROR:
      return {
        ...state,
        error: null,
      };
    default:
      return state;
  }
};

商店

const reducer = combineReducers({
products:productsReducer,
product: productReducer,
})

ProductList.js

import React, { Fragment, useEffect } from 'react'
import { useSelector, useDispatch } from "react-redux";
import SideBar from "./Sidebar";
import {
  clearErrors,
  getAdminProduct,
  deleteProduct
} from "../../Actions/productAction";
import { Link,} from "react-router-dom";
import './ProductList.css'
import { DELETE_PRODUCT_RESET } from "../../Constants/productConstant";
import { useNavigate } from 'react-router';

const ProductList = () => {

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { error, products } = useSelector((state) => state.products);
  const { error: deleteError, isDeleted } = useSelector(
    (state) => state.product
  );

  useEffect(() => {
    if (error) {
      alert(error);
      dispatch(clearErrors());
    }
    if (deleteError) {
      alert(deleteError);
      dispatch(clearErrors());
    }

    if (isDeleted) {
      alert("Product Deleted Successfully");
      navigate("/admin/dashboard");
      dispatch({ type: DELETE_PRODUCT_RESET });
    }
    dispatch(getAdminProduct());
  }, [dispatch,error,deleteError,isDeleted]);
  return (
    <Fragment>
      <div className='adminproductlistedit'>
      <div className='table_overflow'>
        <table id='table'>
          <thead> {/* The Head of The Table  */}
            <tr>
              <th className='editTable editProductId'>Product ID</th>
              <th className='editTable editName'>Name</th>
              <th className='editTable editStock'>Stock</th>
              <th className='editTable editCategory'>Category</th>
              <th className='editTable editPrice'>Price</th>
              <th className='editTable adminActions'>Actions</th>
            </tr>

          </thead>{/* End of The Head  */}
          <tbody> {/* The Body of The Table  */}

            {products &&
              products.map((item) => (
                <tr className='tr'>
                  <td>{item._id}</td>
                  <td>{item.name}</td>
                  <td>{item.stock}</td>
                  <td>{item.category}</td>
                  <td>{item.price}</td>
                  <td className='actiondiv'>
                    <button><Link to={`/admin/product/${item._id}`}>
                      Edit <i className=" editicon fa-solid fa-pencil" />
                    </Link></button>

                    <button onClick={() => {
                    dispatch(deleteProduct(item._id))}}
                    >Delete <i className="deleteicon fa-solid fa-trash-can" /></button>
                  </td>
                </tr>
              ))}
          </tbody>
        </table>
        </div>
      </div>
    </Fragment>
  )
}
export default ProductList

您应该将 DELETE 路线声明为 delete 请求:

router
  .route('/admin/product/:id')
  .put(isAuthenticatedUser, authorizeRoles('admin'), updateProduct)
  .delete(isAuthenticatedUser, authorizeRoles('admin'), deleteProduct);

此外,您可以使用 findByIdAndDelete:

来简化您的控制器
exports.deleteProduct = catchAsyncError(async(req,res,next) => {
    await Product.findByIdAndDelete(req.params.id)
    res.status(200).json({
        success:true,
        message:"product deleted successfully"
    })
})