简体   繁体   中英

When uploading a file in POST, req.body is {} in Node js

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM