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

345
Vistas
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 Respuestas
Responde la pregunta

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 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