Skip to content Skip to sidebar Skip to footer

Using Fetch To Post Cross-origin Json Data To Express Backend

I'm trying to use Fetch to post some JSON data from a form and log the response from the Express server, which should be a simple JSON response containing the posted form values, b

Solution 1:

You can not POST a plain javascript object.

But, please do check all possible values of Content-type as defined in RFC 1341 with the list of mime types.

According to MDN

Fetch body data type must match "Content-Type" header.

Try this code instead.

const form = document.getElementById("myForm");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  var data = {
    firstName: e.target.firstName.value,
    lastName: e.target.lastName.value
  }

  fetch("http://localhost:5000/form-post", {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: JSON.stringify(data)
    })
    .then((res) => res.json())
    .then((data) =>console.log(data));
});

Post a Comment for "Using Fetch To Post Cross-origin Json Data To Express Backend"