"Encountering an issue with Multer where req.file is displaying as undefined in NodeJS

Recently, I followed the advice of several YouTubers and used multer for file upload in my project. However, despite correctly defining all the functions, req.file always appears as undefined.

booking_route.js

const express = require('express');
const router = express.Router();
const multer = require('multer');

// Storage
const storage = multer.diskStorage({
    destination: function (request, file, callback) {
       callback(null, './public/uploads/images')
    },
    filename: function (request, file, callback) {
       callback(null, Date.now() + file.originalname)
    }
 })

 // Upload Params
 const upload = multer({
     storage: storage,
     limits: {
        fileSize: 1024 * 1024 * 3
     }
 })

 const { bookHallForEvent } = 
  require('../controllers/booking_controller')


  router.post('/events', upload.single('image'), bookHallForEvent)

  module.exports = router

booking_controller.js

const eventModel = require('../models/event_model')

const bookHallForEvent = async (req, res) => {
   try {
    console.log(req.file);
    const { hallID, timeSlot, date, name, description, username } = 
     req.body;
    const oldEvent = await eventModel.findOne({ hall_id: hallID, date: 
    date, time_slot: timeSlot })
    if (oldEvent) {
        res.status(400).json({
            error: "Event already booked in the same date and timeslot 
     for this venue"
        })
        } else {
        const event = await eventModel.create({
            name,
            description,
            date,
            time_slot: timeSlot,
            hall_id: hallID,
            user_id: username
          })
        res.status(201).json({
            event_res: event
        })
            }
         } catch (err) {
         console.log(err);
        }

           }

         module.exports = {
      bookHallForEvent
       }

IndividualHallView.vue

<form
        @submit.prevent="handleBooking"
        method="POST"
        enctype="multipart/form-data"
      >
        <div class="modal-body">
          <div class="mb-3">
            <label for="BatsmanLabel" class="form-label">Event name</label>
            <input
              type="text"
              class="form-control"
              v-model="bookingData.event_name"
              id="NameInput"
            />
          </div>
          <div class="mb-3">
            <label for="BowlerLabel" class="form-label"
              >Event Description</label
            >
            <textarea
              class="form-control"
              id="exampleFormControlTextarea1"
              v-model="bookingData.event_desc"
              rows="3"
            ></textarea>
          </div>

          <div class="mb-3">
           ... (Additional code snippets continue here) ...
          </div>
        </div>
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-secondary"
            data-bs-dismiss="modal"
          >
            Cancel
          </button>
          <button data-bs-dismiss="modal" class="btn btn-primary">
            Submit
          </button>
        </div>
      </form>

I hope this issue is just a minor bug causing the problem.

P.S. Apologies for the inconsistent code formatting.

Answer №1

To send a request with `multipart/form-data` that Multer can understand, you must create a FormData object. This piece of code will handle your file input along with all the inputs supported by the `bookingData` models.

methods: {
  async handleBooking({ target }) {
    // capturing all named inputs in your form, such as
    // <input type="file" name="image" />
    const data = new FormData(target);

    // adding other form data
    data.append("name", this.bookingData.event_name);
    data.append("description", this.bookingData.event_desc);
    data.append("date", this.bookingData.event_date);
    // and so on

    try {
      const res = await fetch("/api/events", {
        // URL is just a guess
        method: "POST",
        body: data,
      });

      if (!res.ok) {
        throw new Error(`${res.status}: ${await res.text()}`);
      }

      const { event_res } = await res.json();

      // handling event_res, for example
      console.log("event created", event_res);
    } catch (err) {
      console.error("handleBooking", err);
    }
  }
}

If you are using Axios instead of `fetch`, the relevant part of the code would resemble this:

try {
  const { data: { event_res } } = await axios.post("/api/events", data);
  // handling event_res, for example
  console.log("event created", event_res);
} catch (err) {
  console.error("handleBooking", err.toJSON());
}

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

Trying to access a frame with URL from JavaScript in the same domain in an unsafe manner

I am encountering an issue while attempting to access the URL of the parent window from an iFrame. The error message I received on my server is as follows: Unsafe JavaScript attempt to access frame with URL from frame with URL . The frame being acc ...

The issue with history.push() functionality not functioning as expected within Firebase's authentication system when used in conjunction

I'm currently working on setting up authentication using React, Firebase Auth, and Context API. signin.js import React, { useEffect, useState } from 'react'; import { Form, Button, Container, Card } from 'react-bootstrap'; import ...

Blunder! Error code EINVALIDTAGNAME encountered while trying to install a package

I'm encountering an issue while trying to add a new package to my React application. The error I'm receiving is: $ npm install xlsx npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "react-scripts start": Tags may not have any characters th ...

When working with NextJs, you may encounter a ValidationError indicating that the configuration object is invalid. This error occurs when Webpack has been initialized with a configuration object that doesn't

After upgrading from Next v12 to v12.2.3, I encountered a problem when running "yarn dev" with a new middleware.js file in the root directory: ValidationError: Invalid configuration object. Webpack initialization error due to mismatched API schema. - Deta ...

The user removal process is not functioning properly

I'm encountering an issue in my Angularfire project while trying to remove a user. The email and password are being passed correctly, but the method responsible for user removal isn't getting executed. Below is the snippet of code from my Authent ...

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Enhance the step implementation in Cucumber-js

Background In my TypeScript project, I am utilizing https://github.com/cucumber/cucumber-js. The code snippet below showcases a typical cucumber implementation: import { Given, Then, When } from 'cucumber' Given(`Page is up and run ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

The positioning problem arising from using a Vuetify select dropdown within a datatable

Vuetify datatable is being used with 20 columns, functioning properly. To view all the columns, horizontal scrolling is available. Filters are needed for each column in the header, achieved using v-slot:header. An issue arises when clicking on the select ...

Access to the server has been restricted due to CORS policy blocking: No 'Access-Control-Allow-Origin'

I’m currently encountering an issue with displaying API content in Angular and I’m at a loss on how to troubleshoot it and move forward. At this moment, my main objective is to simply view the URL data on my interface. Does anyone have any insights or ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

Accessing child component data from within a parent component in Vue 2

I am currently utilizing vue2 in my project development. Upon the component mounting (or beforeMount), it fetches initial data from vuex and stores it in the component's data. When the user clicks a button, it triggers the parent's method. How c ...

One way to showcase a single piece of data without the need for looping is by utilizing the `

I am encountering an issue. Why does the insertAdjacentHTML("afterend") output keep looping? I only want to display "1" once, not repeatedly. var btn = document.getElementById("btnClick"); btn.addEventListener("click", function (e) { e.preventDefaul ...

CodePen experiencing issues with JS/jQuery coding functionality

Experimenting on CodePen, I am practicing using JS and jQuery with HTML. HTML: <button>asdasads</button> JS: $('button').on('click', function() { alert('woot'); }); Visit this pen, unfortunately it's ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

Issue with React Redux: Passing down a component's method to its children results in an undefined error

Currently, I am working on creating a todo list using React and Redux. In my code snippet provided below, there is a component that includes a function called onDeleteItem. The issue I am facing is the inability to pass the onDeleteItem function to the s ...

Struggling to remove a column from my Mysql database table

I've exhausted all my options, but I still can't seem to delete data from my MySQL table using axios.delete with ProjectId (table ids). Below is the code snippet where I define my function and pass it through props: import React from "react"; im ...

Ensuring scroll position remains fixed post screen rotation in HTML/Javascript

Is there a foolproof method to retain the scroll position in an HTML document following a screen rotation? While this issue is specifically in a Cocoa Touch UIWebView, it seems to be prevalent across different platforms. The standard practice appears to re ...