A Beginner's Guide to Sending and Handling JSON Objects in Frontend and Backend

First, let's create a simple frontend that uploads the JSON file to the backend.

The form element is the main focus of this code snippet. It includes the following attributes:

  • action: This specifies the URL where the form data will be submitted. In this case, the URL is set to "localhost:3000/upload", but you'll need to replace this with the appropriate URL for your server-side script.

  • method: This specifies the HTTP method used to submit the form. In this case, it's set to "post" to ensure the file data is sent securely.

  • enctype: This specifies the type of encoding used for the form data. In this case, it's set to "multipart/form-data" to allow for file uploads.

The input element is where users will select the file they want to upload. It includes the following attributes:

  • id: This is used to associate the label with the input, as mentioned above.

  • name: This specifies the name of the file input field, which will be used in the server-side script to access the uploaded file (pay special attention to this attribute).

  • type: This is set to "file" to allow users to select a file from their device.

Finally, there's a submit button that users can click to upload the selected file.


Now let's build the backend to handle the form submission.

const express = require("express");
const multer = require("multer");
const fs = require("fs");
const app = express();

const storage = multer.diskStorage({
  destination: "uploads/",
  filename: (req, file, callback) => {
    callback(null, file.originalname);
  },
});

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

app.post("/upload", upload.single("file"), (req, res) => {
  const file = req.file;

  fs.readFile(file.path, "utf-8", (err, data) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ message: "Error reading file" });
    }

    console.log(data);
    res.status(200).json({ message: "File uploaded successfully" });
  });
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

This code is for creating an endpoint that allows users to upload a file from the frontend and handle it on the backend. It uses the Express.js framework for creating the server, Multer for handling file uploads, and the built-in fs module for reading and writing files.

Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. In this code, Multer is configured to use diskStorage to specify where uploaded files should be stored, and to use the original filename of the uploaded file.

The multer.diskStorage function is used to specify the destination folder and the naming convention for the uploaded files. In this case, the destination folder is set to uploads/ and the name of the uploaded file is set to its original name.

The upload object is created using multer({ storage: storage }) and is used as middleware in the POST request to /upload. upload.single("file") specifies that only one file can be uploaded with the name "file".

Note -

The reason why the code doesn't use body-parser is that it is designed to handle JSON and URL-encoded form data, not files. Multer is specifically designed to handle file uploads and provides more robust functionality for handling files, including file size limits, file type validation, and more. Therefore, multer is a better option for handling file uploads than body-parser.

Did you find this article valuable?

Support Balveer Singh Rao by becoming a sponsor. Any amount is appreciated!