Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'image' of null

I know that this issue is related to the use of async/await, but I am unsure how to properly rewrite it or identify the specific problem. Can someone please help me understand and fix it?

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("/");
});

Answer №1

The reason you are experiencing this issue is not due to async/await, but rather because your request does not contain any .files. To resolve this, you will need to use a middleware for handling multipart/form-data such as multer. You can then pass the middleware in the app.post so that you can access req.files. If you would like to upload the image to a server like cloudinary, you can utilize multer-cloudinary-storage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...

Evaluating the functionality of express.js routes through unit testing

Just dipping my toes into the world of express and unit testing. Take a look at this code snippet: const express = require('express'); const router = express.Router(); const bookingsController = require("../controllers/bookings"); router .r ...

Launch a dialogue box by clicking on the buttons corresponding to the article ID

I am currently in the process of setting up an admin panel with some quick actions for managing my articles, such as deleting them. When I click on the trash can icon, a dialog box should open and prompt me to confirm the deletion. This dialog box should b ...

Refreshing webpage content by utilizing iframes

I am looking for a way to completely clear a webpage using either Javascript or PHP. However, there seems to be an issue with a specific area of the page that is marked as: data-form="manual iframe" When attempting to clear the page, only the data within ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...

IE displaying "slow script" alert due to Knockout malfunction

Within my grid of observables and computed observables, the first row serves as a multiplier for all subsequent rows. Users can modify this percentage rate and Knockout automatically updates all relevant values accordingly. Additionally, I require a textbo ...

Error encountered: When trying to pass an event and two variables, the function e.preventDefault is not recognized as a valid

As a beginner in JS, I thought I had event handlers figured out. After hours of searching for a solution, I'm stuck. I'm trying to create a carousel, and while it mostly works, when I attempt to pass an event handler and two variables from one fu ...

Chrome's XPath attribute selection is not functioning properly

After running a small test with expect.js, here are the results: describe('xpath', function () { it('locates attribute nodes', function () { $(document.body).append('<string fooBar="bar"><data id="xyz">< ...

Strange Scrolling Issues in Blackberry Webworks when Using Touchscreens

Within my Blackberry Webworks app designed for Smartphones OS 6, 7, and 7.1, there is a portion of code that looks like this: <div style="width:100%; height:100%; overflow:hidden;"> <div style="overflow:auto;height:100px;width:100%;"> ...

Error encountered during Next.js project build: Entry point specified for implicit type library 'build'

While working on my nextjs project, I encountered the following error: Type error: Cannot find type definition file for 'build'. The file is in the program because: Entry point for implicit type library 'build' Can someone guide ...

I am encountering difficulties with hosting a project that was created using Next.js

I am currently working on a Next.js project and I encountered some version compatibility issues when integrating MUI. While my project runs smoothly in localhost, it fails to work when deployed in hosting. I attempted to resolve this by using the --legacy ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

Echarts: Implementing a Custom Function Triggered by Title Click Event

I recently created a bar graph using Echart JS, but I'm struggling to customize the click event on the title bar. I attempted to use triggerEvent, but it only seems to work on statistics rather than the title itself. JSFiddle var myChart = echarts.i ...

Adapting JavaScript functions from IE to work on Firefox and Chrome: A comprehensive guide

I have encountered an issue with a function that retrieves the selected text range within a contenteditable div. While it works perfectly fine in Internet Explorer, it doesn't seem to work in Firefox and Chrome. Could someone kindly provide guidance ...

Get the username from Parse instead of using the ObjectID

When using angular and Parse for JavaScript, I have implemented a search field where an admin can input the objectid of a user to display their details. However, I would like to modify this functionality so that the admin can enter the username instead of ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...