0

I used multer to save the file which uploaded by user in my middlewares the req.body is empty object I used express.json() in my app.js

and i am using formdata method with Postman everything went good when i used normal json but thats wont help me because my file will not upload my middleware

const User = require(`../models/user`);
module.exports = async (req, res, next) => {
console.log(req.body);
const user = await User.findOne({ email: req.body.email });
if (user) {
const error = new Error(`User already exists. Middleware`);
error.statusCode = 500;
return next(error);
}
next();
};
const User = require(`../models/user`);

module.exports = async (req, res, next) => {
console.log(req.body);
const user = await User.findOne({ email: req.body.email });
if (user) {
const error = new Error(`User already exists. Middleware`);
error.statusCode = 500;
return next(error);
}
next();
};

the route

const express = require(`express`);
const multer = require(`multer`);

const notAuth = require(`../middlewares/not-auth`);

const isAuth = require(`../middlewares/is-auth`);

const checkIfUpload = require(`../middlewares/check-if-upload`);

const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images/users");
},
filename: (req, file, cb) => {
cb(null, Date.now().toString() + `-` + 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);
}
};

const upload = multer({ storage: fileStorage, fileFilter: fileFilter });

const authController = require(`../controllers/auth`);

const router = express.Router();

router.post(
`/signup`,
checkIfUpload,
notAuth,
upload.single("image"),
authController.signup
);

module.exports = router;
  • `req.body` will be empty as long as `upload.single()` isn't being called. So if you mean that it's empty in `checkIfUpload` or `notAuth` (your question isn't clear about that), you need to move them _after_ `upload.single()`. – robertklep Aug 31 '22 at 15:26
  • it is empty object in both, the problem is i created this middleware to stop uploading image in signup if the user exists so i surely want this middleware before upload.single() or maybe i want to adjust something in controller so the image dont upload when the user exists ? – Mohammad ARZ Aug 31 '22 at 15:27
  • If you need _some_ parts of a multipart request body, you'll have to accept that it will be uploaded in full. The only thing you can do is use a [file filter](https://github.com/expressjs/multer#filefilter) to tell `multer` to skip the file data, but you can't prevent the actual data to be uploaded. – robertklep Aug 31 '22 at 15:32

0 Answers0