Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
React not finding Express server delete request. (MERN delete problem)

Express/Node Code:

app.delete("/inventory/:id", async (req, res) => {
    const id = req.params.id;
    const query = { _id: ObjectId(id) };
    const result = await inventoryCollection.deleteOne(query);
    res.send(result);
  });

React Code


    const handleDelete = (id) => {
    const url = `http://localhost:5000/inventory/${id}`;
    fetch(url, { method: "Delete" })
      .then((res) => res.json())
      .then((data) => {
        if (data.dataCount > 0) {
          console.log("deleted");
          const remaining = products.filter((service) => service._id !== id);
          setProducts(remaining);
          console.log(data);
        }
      });
  }

    <FontAwesomeIcon
                  icon={faTrashAlt}
                  className="delete-font"
                  onClick={() => handleDelete(product._id)}
                />

Error Message:
DELETE http://localhost:5000/inventory/62716639288c1342383e563a 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I can't find anything wrong. But it's not working.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First, console.log what exactly is being sent to the server, what you receive, in order to understand what's going on. This will help you track down the error (take a close look at the console.log I've put below):

    const handleDelete = (id) => {

    console.log("Am I sending the correct id?", id ); // <= debugging

    const url = `http://localhost:5000/inventory/${id}`;

    console.log("Is the URL formatted correctly?", url); // <=debugging

    fetch(url, { method: "Delete" })
      // .then((res) => res.json()) //Let's replace json() with text() to see the actual response in any case 
      .then((res) => res.text())
      .then((data) => {

        console.log("What exactly comes back from the server?", data); // <= debugging

        if (data.dataCount > 0) {
          console.log("deleted");
          const remaining = products.filter((service) => service._id !== id);
          setProducts(remaining);
          console.log(data);
        }
      });
  }

<FontAwesomeIcon
 icon={faTrashAlt}
 className="delete-font"
 onClick={() => handleDelete(product._id)}
/>

Also, debug the backend with a few more console.logs to see what's happening on that side. Along with the logs, put a try catch around the await operation to see if anything breaks:

app.delete("/inventory/:id", async (req, res) => {

  console.log("Is this  endpoint ever get hit?"); <= debugging

    const id = req.params.id;

  console.log("Do I get the ID I expect?", id ); <= debugging

    const query = { _id: ObjectId(id) };
    try {
      const result = await inventoryCollection.deleteOne(query);
      console.log("What comes out of deleteOne operation?", result); <= debugging
    } catch (e){
      console.log("Ops! Something went wrong with the deleteOne operation"); <= debugging
    }
    res.send(result);
  });

These logs will help you pinpoint, where something goes wrong and leads to the error that you see on the console.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda