I want to send product data including an image to the database. I am using multer and get the error:
Cannot read property ‘path’ of undefined
I have seen that this error is very common and have tried the suggestions that are made on stack overflow without success. What makes me suspicious is, when I log the req.body, the correct data is displayed, but image is an empty object. I also logged the whole thing in my http-request, there image is a file and prototype array.
multer storage:
import { Request } from "express";
import multer, { FileFilterCallback } from "multer";
import path from 'path'
const maxSize = 100 * 1024 *1024;
type DestinationCallback = (error: Error | null, destination: string) => void
type FileNameCallback = (error: Error | null, filename: string) => void
const storage = multer.diskStorage({
destination:(req:Request,file:Express.Multer.File, callback:DestinationCallback)=>{
callback(null, path.resolve(process.cwd(), 'admin/public/uploads'));
},
filename: (req:Request, file:Express.Multer.File, callback:FileNameCallback)=>{
callback(null, Date.now()+ "--"+ path.extname(file.originalname))
},
})
const upload = multer({
storage:storage,
fileFilter:(req:Request,file:Express.Multer.File,callback:FileFilterCallback)=>{
if(
file.mimetype == "image/png"||
file.mimetype == "image/jpg" ||
file.mimetype == "image/jpeg" ||
file.mimetype == "video/mp4"
){
callback(null, true);
} else{
callback(null,false)
return callback(new Error("Only .png, .jpg, .jpeg, .mp3, .mp4 allowed"))
}
},
limits:{fileSize: maxSize}
});
export default upload
;
My route:
productsRouter.post('/', upload.single('image'), verifyTokenAndAdmin, async (req:Request, res:Response)=>{
console.log(req.file);
console.log(req.body);
try{
const uploadResult = cloudinary.uploader.upload(req.file!.path,{
upload_preset: "webshop_ts_mern",
resource_type: "auto",
})
const newProducts = new Products({
cloudinary_id: uploadResult.public_id,
title: req.body.title,
producer: req.body.producer,
categories: req.body.categories,
desc: req.body.desc,
price: req.body.price,
currency:req.body.currency,
colors:req.body.colors,
sizes: req.body.sizes,
inStock: req.body.inStock,
image: uploadResult.secure_url,
})
const savedproducts = await newProducts.save();
res.status(200).json(savedproducts);
} catch(error){
res.status(403)
console.log(error);
throw new Error("Action failed");
}
});