I am using a call to new FormData()
. The network tab shows that the payload is correct. In the console I am getting the following error:
{message: "Blog validation failed: title: Path `title` is required., postBody: Path `postBody` is required."}
However, in the network tab it's showing that the title and postBody fields are being sent:
The server is written with nodejs and is using mongodb. All the routes are working on the backend when testing. Data is posted fine when testing it using a .rest file, but I'm still new to node so I'll post my handler for the post route as well:
router.post('/', async (req, res) => {
const blogPost = new Blog({
title: req.body.title,
author: req.body.author,
postBody: req.body.postBody,
postDate: req.body.postDate
})
try {
const newPost = await blogPost.save();
res.status(201).json(newPost);
} catch (err) {
res.status(400).json({ message: err.message })
}
})
Like I said, when making calls to this route directly using a .rest file everything works fine.
Here's my form submit handler on the frontend:
handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.target);
console.log(event.target);
console.log(data);
console.log(event.target.postBody.value);
fetch('http://localhost:4000/blog', {
method: 'POST',
mode: 'cors',
body: data
})
.then(res => res.json())
.then(err => console.error(err))
}
Maybe I misunderstand the usage of new FormData()
?