Home > Software design >  500 - internal server error my API is not working
500 - internal server error my API is not working

Time:01-29

I make a crud with products

I send an http request to the /api/deleteProduct route with the product id to retrieve it on the server side and delete the product by its id

To create a product it works only the delete does not work

pages/newProduct.js :

useEffect(() => {
    async function fetchData() {
      const res = await axios.get('/api/products');
      setProducts(res.data);
    }
    fetchData();
  }, []);

  const handleSubmit = async (event) => {
  event.preventDefault();
  const formData = new FormData();
  formData.append('picture', picture);
  formData.append('name', name);
  formData.append('price', price);
  formData.append('category', category);
  formData.append('description', description);
  try {
  const res = await axios.post('/api/createProduct', formData);
  console.log(res.data);
  } catch (error) {
  console.log(error);
  }
  };
  const handleDelete = async (id) => {
    try {
      await axios.delete(`/api/deleteProduct?id=${id}`);
      setProducts(products.filter(product => product._id !== id));
    } catch (error) {
      console.log(error);
    }
  };

api/deleteProduct.js :

import Product from '../../models/Products';
import { initMongoose } from '../../lib/mongoose';

initMongoose();

export const handleDelete = async (req, res) => {

  if (req.method === 'DELETE'){
  try {
 
    const { id } = req.params
    
    const product = await Product.findByIdAndRemove(id);
    if (!product) {
      return res.status(404).json({ message: 'Product not found' });
    }
    return res.status(200).json({ message: 'Product deleted successfully' });
  } catch (error) {
    console.log(error);
    return res.status(500).json({ message: 'Database error' });
  }
}};

I have a 500 error but no error in the server side console and the console.log is not showing like the file was not read

CodePudding user response:

Based on the code you've shared, it seems that the problem may be with the way that the delete request is being handled on the frontend. Specifically, in this line:

await axios.delete("/api/deleteProduct", { params: { id } });

The delete request is supposed to receive the id of the product that should be deleted as a query parameter, but it is being passed as a request body.

Instead of passing it as a parameter, you should pass it as a query parameter by changing it to

await axios.delete(`/api/deleteProduct?id=${id}`);

Also, in your api/deleteProduct.js, you should change the following line:

const { id } = req.query;

to const { id } = req.params;

Also, you should make sure that the server is running and that the api endpoint '/api/deleteProduct' is accessible and handling the request correctly.

For the last, make sure that the product model is imported and initialized correctly and the database connection is established.

Hope that it solves your problem or, at least, helps :))

CodePudding user response:

I succeeded, I put this (server side):

const { id } = req. query;

and (client side):

await axios.delete(/api/deleteProduct?id=${id});

and I exported my function like this:

export default async function handleDelete(req, res) {

  • Related