I test a post with filename but in postman if I don't add image then I have an image undefine, that is ok. But I can't send it if the image don't pass as null.
Here is my controller with filename
module.exports.createComment = async (req, res) => {
try {
if (!req.body.message) {
res.status(400).send({
message: "Content can not be empty!"
});
}
let { id, message, date, image} = req.body;
image = `${req.protocol}://${req.get("host")}/images/${req.file.filename}`,
Comment.create({
id, message, date, image
}).then((comment) => res.status(201).send(comment))
} catch (error) {
console.log(error);
return res.send(`Error: ${error}`);
}
};
My response without image on Postman : Error: TypeError: Cannot read property 'filename' of undefined
CodePudding user response:
You should check the req.file
because access filename
. Because when you don't pass it, req.file
will be undefined
which cannot access filename
let { id, message, date, image } = req.body;
if (req.file) {
image = `${req.protocol}://${req.get("host")}/images/${req.file.filename}`
} else {
image = null;
}