Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda