I want to create a post and upload an image if it is provided.
If I do upload the image everything works fine but if I don't I get this error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'image' of null
I understand it's to do with async/await but I do not know how to rewrite it or that the problem is specifically?
app.post("/posts/create", async (req, res) => {
let image = req.files.image;
if (image !== null) {
image.mv(
path.resolve(__dirname, "public/images", image.name)
);
}
await Post.create(req.body);
res.redirect("/");
});
That's not because async/await, it is simply because you don't have any .files in your request, so you just need a middleware for handling multipart/form-data like multer, and then pass the middleware through the app.post so you can access to req.files, if you want to upload that image to a server like cloudinary you can just use multer-cloudinary-storage.