Vladislav Metnev
Vladislav Metnev

Reputation: 37

Sending form data using fetch

I am trying to send form data using fetch. I have the following code:

var toSend = new FormData();
toSend.append('person', 'Peter');
toSend.append('age', '22');
toSend.append('thistext', 'smart');

fetch('http://localhost:3000/sendform', {
    method: 'POST',
    body: toSend
}).then(res => console.log(res));

And then I am trying to read form data on the backend side with Express using the following code:

app.post("/sendform", function(req, res) {
    console.log("processing form data");
    console.log(req.body);
    res.status(200).send("received");
});

I do have body-parser and etc. However, req.body is an empty object. Can anybody help to fix it?

Upvotes: 0

Views: 76

Answers (1)

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5590

Try this type.

 fetch(config.DOMAIN + "user/addPost", {
        method: "POST",
        headers: {
          "content-type": "application/json"
        },
        body: JSON.stringify(postData)
      })
        .then(res => res.json())
        .then(post => {
          console.log(post)
        })
        .catch(err => {
          console.log(err)
        });

Upvotes: 1

Related Questions