I'm building a Node.js + Express backend where users can upload profile pictures using Multer. When I send a POST request from Hoppscotch to /update_profile_picture, I get this error:
Cannot read properties of undefined (reading 'filename')
router/user.routes.js:
import { Router } from "express";
import { uploadProfilePicture } from "../controllers/user.controller.js";
import multer from "multer";
const router = Router();
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, "uploads/"),
filename: (req, file, cb) => cb(null, file.originalname),
});
const upload = multer({ storage });
router.post("/update_profile_picture", upload.single("profile_picture"), uploadProfilePicture);
export default router;
controller/user.controller.js:
export const uploadProfilePicture = async (req, res) => {
const { token } = req.body;
try {
const user = await User.findOne({ token });
if (!user) return res.status(404).json({ message: "User not found" });
user.profilePicture = req.file.filename; // <-- error happens here
await user.save();
res.json({ message: "Profile Picture Updated" });
} catch (err) {
res.status(500).json({ message: err.message });
}
};
Checked that my form uses
multipart/form-dataField name in Hoppscotch is
profile_pictureAdded
console.log(req.file)— it's always undefinedTried both Postman and Hoppscotch
Why is req.file undefined even though I'm uploading a file correctly with Multer? Do I need to configure something extra for Hoppscotch or Express?