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

342
Visualizações
How to send and receive formData through fetch to node and express?

I am trying to send formData via the fetch API to a node/express app, and use that data to update a database. I can't access the formData in node. If someone could kindly point out what I am doing wrong? I have followed several other answers but none have helped.

I am using javascript to attach an event listener to the submit button, and then access the fetch API. The code below results in an empty req.body.

My html form:

<form
  action=""
  method="POST"
  name="editQuestionForm"
  id="editQuestionForm"
  class="inputForm"
>
  <input
    type="text"
    id="editInputQuestion"
    name="question"
    value=""
    class="formInput"
    placeholder="Question"
  />
  <textarea
    type="text"
    id="editInputAnswer"
    name="answer"
    value=""
    class="formInput"
    placeholder="Answer"
  ></textarea>
  <button id="editQuestionBtn" class="button" type="Submit">
    Edit Question
  </button>
</form>

My javascript:

const editQuestionForm = document.getElementById("editQuestionForm");
const editQuestionBtn = document.querySelector("#editQuestionBtn");

editQuestionBtn.addEventListener("click", function (e) {
  id = e.target.getAttribute("data-id");
  updateQuestion(e, id);
});

async function updateQuestion(e, id) {
  e.preventDefault();
  var formData = new FormData(editQuestionForm);
  dataToSend = Object.fromEntries(formData);
  await fetch(`/dbControl/editQuestion?id=${id}`, {
    method: "POST",
    body: JSON.stringify(dataToSend),
  });
}

My endpoint in my node/express app:

router.post("/editQuestion", function (req, res) {
  try {
    console.log(req.body);
  } catch (err) {
    console.log(err);
  } finally {
    res.end();
  }
});
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Content-Type

You aren't sending a FormData object. You are sending JSON.

You are passing a string to the body property so you need to explicitly say that you are sending JSON. fetch cannot infer that your string is JSON.

This step wouldn't be needed if you were sending multipart form data by passing a FormData object, nor if you were sending URL Encoded data by passing a URLSearchParams object. fetch can infer the content-type from those objects.

await fetch(`/dbControl/editQuestion?id=${id}`, {
    method: "POST",
    body: JSON.stringify(dataToSend),
    headers: {
        "Content-Type": "application/json"
    }
});

Body Parsing Middleware

As per the documentation:

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

… you need to include some body parsing middleware.

app.use(express.json());

(And do it before you register the end point handler).

about 4 years ago · Santiago Trujillo 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