I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID.

However, the issue lies with creating a new product as the functionality seems to be broken. The pages/newProduct.js file contains the code for fetching and submitting product data.

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);
    }
  };

The api/deleteProduct.js file handles the deletion of a product from the database:

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' });
  }
}};

Despite no errors being displayed on the server side console, I encounter a 500 error while trying to perform certain actions. Additionally, console logs do not appear as expected, indicating that the file may not have been read properly.

Answer №1

After reviewing the code you've provided, it appears that the issue may lie in how the delete request is processed on the frontend side. Specifically, there seems to be a problem with this line:

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

The delete request should ideally receive the product's ID as a query parameter, but it is currently being sent in the request body.

To rectify this, you need to modify the code to pass the ID as a query parameter like so:

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

Additionally, within your api/deleteProduct.js file, you should update the following line:

const { id } = req.query;

to

const { id } = req.params;

Furthermore, ensure that the server is up and running smoothly, and that the '/api/deleteProduct' endpoint is functioning correctly.

Last but not least, double-check that the product model is imported and initiated accurately, and that the database connection is established properly.

I hope these adjustments help resolve your issue or at least point you in the right direction :))

Answer №2

After some trial and error, I managed to implement the following on the server side:

const { identifier } = req.params;

On the client side, I incorporated the following code:

await axios.delete(

/api/removeItem?identifier=${identifier}
);

To wrap it all up, I exported my function in this manner:

export default async function handleRemove(req, res) {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with exporting to Excel in AngularJS in Internet Explorer not functioning as expected

Having some trouble exporting data to Excel or PDF in IE, but it works fine in Chrome. Since most users will be using Internet Explorer, can someone please review my code and provide suggestions? Below is the Angular function I am using: scope. ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

After a certain time has passed, an event will occur once a div element has been assigned

Is there a way to show div2 only after div1 has been given the '.selected' class for a set duration, and then hide it again when div1 loses the '.selected' class? What would be the most efficient approach to achieve this? ...

Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allo ...

What is the method for triggering two actions within a single linked tag?

I have a link tag structured like this: <a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a> Upon clicking the "Home" link, it should navigate to the dashboard. At the dashboard page, I want to check i ...

Is it possible for an independent perl script to execute a function from a website's javascript?

Looking at this complex setup, I find myself in a situation where I must find a way to trigger the $.ajax function on a webpage using a separate Perl script. The scenario involves a webpage making $.ajax calls to a Perl file, which retrieves data and send ...

Error encountered in MySQL and NodeJS: Unable to add new query after invoking quit with transactions

While working on implementing MySQL for NodeJS and Restify, I encountered a flawless experience with queries. However, when attempting to utilize data updating functionality through transactions, I faced the error message: Error: Cannot enqueue Query after ...

Retrieve the selected options from the checkbox and transfer them to the input text field

In the following example, I am attempting to extract all values of the inputs once they are checked and display them in a text input that will be sent via email. However, I am facing an issue where only the last option is being printed in that input instea ...

Select the hidden HTML option value automatically according to the previous option selected

I am working on a form that includes 2 select tags with the options male and female. The first select, "gender", is visible to the user while the second select, "age", is hidden. <select name="gender"> <option value="1">Male</option> ...

When copying text from React-PDF Display, the values may appear altered or varied

This snippet of text was excerpted from a brief SHA provided at the git summit. Generated using React-pdf, this is a PDF document with some interesting quirks. Although the displayed text reads as 4903677, it changes to •G07THH when copied. The font ...

Ensure that both textarea and pre elements have equal dimensions and line wrapping behavior in Internet Explorer

I am in the process of implementing a dynamic textarea that resizes automatically, based on a technique discussed in this article: Alistapart: Expanding Textareas (2011). The idea is quite straightforward: by using a pre element to mirror the input in the ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

The issue persists with the event listener not responding to input key

Can the Keycode that is pressed during the firing of addEventListener input be retrieved? <p contentEditable="true" id="newTask">New task</p> document.getElementById("newTask").addEventListener("input" ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...