3

React code - FileUploader.js

// React - FileUplader.js

    const handleSubmission = (e) => {
        e.preventDefault();
        if(isSelected === false){
            alert("load the file");
        }
        else{
            const formData = new FormData();
            formData.append("certificate",selectFile);

            // API CALL
            fetch("http://localhost:8080/upload", {
                method: "POST",
                body: formData,
                headers : {
                    "Content-Type" : "multipart/form-data"
                }
            }).then((response) =>response.json())
            .then((result)=>{
                console.log("Success : ", result);
            })
                .catch((error)=>{
                    console.error("Error : ",error);
                });
        }
    };

Nodejs code - Server.js

app.use(cors()); 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));

app.post('/upload', async function(req ,res){
    try {
        const file = req.files; // undeifined
        const bodyData = req.body; // {}
        console.log("file : ",file);
        console.log("bodyData : ",bodyData);

        res.status(200).send({
            message: "FILE RECEIVED!"
        });
    } catch(error){
        res.send("ERROR")};
});

Problem

Why req.body is {} in node js

I tried using MULTER but got the same result

MDN says that FormData object is not a simple object, but a special object created for XMLHttpRequest transmission and cannot be recorded with the console.

Kite_Z
  • 47
  • 1
  • 6

1 Answers1

1

Your front end code is correct. You did not set up multer. Multer is actually a middleware, will be listening to multipart/form-data. [check the docs][1]

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.

Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

to handle files on node.js environment, write a middleware:

const multer = require("multer");
const { randomBytes } = require("crypto");

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, randomBytes(4).toString("hex") + "-" + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

module.exports = multer({ storage: fileStorage, fileFilter }).single("image"); //image is the field name

Then use it in express app

const multer = require("./middlewares/multer");

app.use(cors()); 
app.use(bodyParser.json());
app.use(multer);

app.use(bodyParser.urlencoded({extended : true}));

[1]: http://expressjs.com/en/resources/middleware/multer.html#:~:text=Multer%20is%20a%20node.,multipart%2Fform%2Ddata%20).

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Multer isn't the only option. I actually find [express-fileupload](https://github.com/richardgirges/express-fileupload) a little more beginner friendly – Phil Jul 08 '22 at 00:59
  • Thank you. I was able to solve the problem. – Kite_Z Jul 08 '22 at 01:51