PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

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

 October 14, 2022     axios, express, node.js, post, reactjs     No comments   

Issue

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.


Solution

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



Answered By - Yilmaz
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing