Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I send a form without the image (filename)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading