Home > Net >  express crashes if req.file is undefined
express crashes if req.file is undefined

Time:01-03

when making a post request to an express api without an attached file in the request, the api crashes and provides the TypeError: Cannot read properties of undefined (reading 'filename') error. However i would like to make it so the api does not crash when a post request is made without an attached image. any ideas ?

express code :

const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, dir)
    },
    filename: (req, file, cb) => {
        cb(null, Date.now()   file.originalname)
    }
})

const upload = multer({
    storage: storage
})

router.get('/', async (req, res) => {
    try {
        const members = await Member.find();
        res.json(members);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
})
router.get('/:id', getMember, async (req, res) => {
    res.json(res.member)
})
router.post('/', upload.single('image'), async (req, res) =>{
    const member = new Member({
        name: req.body.name,
        occupation: req.body.occupation,
        bio: req.body.bio,
        join: req.body.join,
        image: req.file.filename
    })
    try {
        const newMember = await member.save()
        res.status(201).json(newMember)
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
})

nextjs code to actually send the file:

const submitHandler = (e) => {
        e.preventDefault()
            const formDatas = new FormData()
            formDatas.append('name', name)
            formDatas.append('occupation', occupation)
            formDatas.append('bio', paragraph)
            formDatas.append('join', date)
            formDatas.append('image', img)
        console.log(formDatas)
        axios
        .post(api   '/members', formDatas)
        .then(res => console.log(res))
        .catch(err => console.log(err))
    }

CodePudding user response:

Change as shown below

 const member = new Member({
        name: req.body.name,
        occupation: req.body.occupation,
        bio: req.body.bio,
        join: req.body.join,
        image: req.file.filename ? req.file.filename : ""
    })

This should stop crashing but until I see the whole code wont know how you are handling error

CodePudding user response:

Error occurred because you're trying to access object of undefined variable req.file;

You can make changes according to your need

1 If you don't want to accept request without any file

router.post('/', upload.single('image'), async (req, res) => {
if (!req.file) { //or you can check if(req.file===undefiend)
    return res.status(400).json({ message: 'Please attach a file' });
}
const member = new Member({
    name: req.body.name,
    occupation: req.body.occupation,
    bio: req.body.bio,
    join: req.body.join,
    image: req.file.filename
})
try {
    const newMember = await member.save()
    res.status(201).json(newMember)
} catch (err) {
    res.status(400).json({ message: err.message });
}

})

2 If you want to store null/empty string (in case of no file upload)

router.post('/', upload.single('image'), async (req, res) => {
const member = new Member({
    name: req.body.name,
    occupation: req.body.occupation,
    bio: req.body.bio,
    join: req.body.join,
    image: req.file!==undefined ? req.file.filename : null
})
try {
    const newMember = await member.save()
    res.status(201).json(newMember)
} catch (err) {
    res.status(400).json({ message: err.message });
}

})

  • Related