Search code examples
javascriptnode.jsfile-uploadmulter

multer middleware does not recognize body of req


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/images");
  },
  filename: (req, file, cb) => {
    console.log(req.body); // <- This will output null object
    cb(null, file.originalname);
  },
});

const upload = multer({ storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
  try {
    return res.status(200).json(req.body);
  } catch (err) {
    console.log(err);
  }
});

Postman request: enter image description here

Console output:

>>>>>>>>>>>>>SERVER STARTED<<<<<<<<<<<<<
(node:3741192) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:3741192) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Connected to MongoDB
[Object: null prototype] {}
::1 - - [08/Jun/2021:12:11:21 +0000] "POST /api/upload HTTP/1.1" 200 23

My problem is that within:

  filename: (req, file, cb) => {
    console.log(req.body); // <- This will output null object
    cb(null, file.originalname);
  },

req.body is an empty object. But it shouldn't? In the postman request, I included a name property.


Solution

  • From the multer documentation:

    Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

    So changing the order in your postman form and putting name before file (you can simply drag/drop the row) will fix the issue.