Search code examples
javascriptnode.jsexpressfetch-api

Post data with Express / fetch


I try to send data to a web server with fetch() on client side and Express on server side.

Client code

let formData = new FormData();
formData.append("key", MY_API_KEY);
formData.append("fileId", 57);

fetch("https://localhost:3001/api", {
    method: "POST",
    body: formData,
})
.then((response) => { console.log (response); })
.catch((error) => { console.error(error); });

Server

app.post('/api', (req, res) => {

  console.log (req.body);
  console.log (req.body.key);
  res.status(200).json({ status: 'success' });
})

On the server side, I get {} for req.body and undefined for req.body.key.

When I look in dev tools on the client side, I see the payload with the key and fileId. But it seems I don't receive the data on the server side and I can't figure out why?

Any help solving this issue?


Solution

  • Since I am not able to comment let me put my approach in the answers section.

    When sending form data using FormData, it's important to understand that on the server-side with Express, you need middleware to parse the form data. You can make use of multer as a middleware.

    const upload = multer();
    
    app.post('/api', upload.none(), (req, res) => {
      console.log(req.body);
      console.log(req.body.get('key'));
      res.status(200).json({ status: 'success' });
    });