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"
>
<input
type="text"
id="editInputQuestion"
name="question"
value=""
placeholder="Question"
/>
<textarea
type="text"
id="editInputAnswer"
name="answer"
value=""
placeholder="Answer"
></textarea>
<button id="editQuestionBtn" 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();
}
});
CodePudding user response:
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).