Treat req.files as null

Asked

Viewed 52 times

1

Good night.
I’m starting now with studies in web development and would like to know how to treat the following:
What I developed was a blog, and in the area of creating posts, there is a form for you to type: Author, Post title, Description and Content.

Below this, there is a button to upload an image, which will be used as the post cover. However, I would like to allow the creation of the post to be done without sending the image. But when filling only the textual fields and not selecting an image, I get the following return:

Typeerror: Cannot destructure Property 'image' of 'req.files' as it is null.

Here are my codes:
storePost.js

const path = require('path')

const Post = require('../database/models/Post')

module.exports = (req, res) => {
    const {
        imagem
    } = req.files

    imagem.mv(path.resolve(__dirname, '..', 'public/posts', imagem.name), (error) => {
        Post.create({
            ...req.body,
            imagem: `/posts/${imagem.name}`
        }, (error, post) => {
            res.redirect('/');
        });
    })
    
}

index js.

const storePostController = require('./controllers/storePost');
app.post('/posts/store', auth, storePostController);
  • This was the tutorial I followed to develop the blog: https://vegibit.com/node-js-blog-tutorial/

1 answer

-1

To make the desired flow you must modify your code to treat the case of not uploading the image.

One way to solve the problem is to check if the property exists before using the value, follow an example:

const path = require('path')

const Post = require('.. /database/models/Post')

module.exports = (req, res) => {
   //quando o req.files estiver definido
   if (req.files) {
       const { imagem } = req.files

       imagem.mv(path.resolve(__dirname, '..', 'public/posts', imagem.name), (error) => {
       Post.create({
            ...req.body,
            imagem: `/posts/${imagem.name}`
            }, (error, post) => {
            res.redirect('/');
            });
        })
   } else {   
       Post.create({...req.body, imagem: null }, (error, post) => {
            res.redirect('/');
       });
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.