submit a post request using formdata to the NodeJS server with a fetch API

Formdata to node js server

Table of contents

No heading

No headings in the article.

To submit a POST request with FormData to a Node.js server using the Fetch API, you can follow this example. In this example, I'll assume you want to send form data to the server and handle it on the server side. This is a common scenario for handling form submissions:

Client-side (HTML and JavaScript):

<!DOCTYPE html>
<html>
<head>
  <title>File Upload Example</title>
</head>
<body>
  <form id="upload-form">
    <input type="text" name="name" placeholder="Name">
    <input type="file" name="file">
    <button type="submit">Upload</button>
  </form>

  <script>
    document.getElementById('upload-form').addEventListener('submit', async (e) => {
      e.preventDefault();

      const form = new FormData();
      form.append('name', e.target.name.value);
      form.append('file', e.target.file.files[0]);

      try {
        const response = await fetch('/upload', {
          method: 'POST',
          body: form,
        });

        if (response.ok) {
          const data = await response.json();
          console.log(data);
        } else {
          console.error('Error:', response.status, response.statusText);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    });
  </script>
</body>
</html>

Server-side (Node.js):

const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads'); // Store files in the 'uploads' directory
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname); // Rename uploaded files
  },
});

const upload = multer({ storage: storage });

// Serve static files from the 'uploads' directory
app.use(express.static('uploads'));

app.post('/upload', upload.single('file'), (req, res) => {
  // The uploaded file information is available in req.file
  const uploadedFile = req.file;

  // Other form fields are available in req.body
  const name = req.body.name;

  // Handle the uploaded file and form data as needed (e.g., store the file, process it)
  // Respond with a JSON response indicating success or any error messages
  res.json({ message: 'File uploaded successfully!', name });
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

In this example:

  1. The client-side HTML form collects user input, including a text input for the name and a file input for the file.

  2. When the form is submitted, JavaScript code gathers the form data into a FormData object and sends it as a POST request to the server using the Fetch API.

  3. On the server-side, the Express.js application handles the POST request at the /upload route. The multer middleware is used to process the file upload, and the uploaded file information is available in req.file, while other form fields are available in req.body.

  4. You can handle the uploaded file and form data as needed, such as storing the file on the server, processing it, or validating the form data.

  5. Finally, the server responds with a JSON message to indicate whether the upload was successful. The client-side JavaScript logs the response to the console.

Make sure you adjust the file paths, port, and other details as needed for your specific application.