Encountering Issues with File Uploads in Express.js with Multer

Currently, I am immersing myself in Node.js through the guidance of a book titled "Web Development with Nodejs and MongoDB." However, I have hit a roadblock when attempting to upload an image using Multer. The code snippet causing me trouble is as follows:

Behold, my Configure.js file:

var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
multer = require('multer');
moment = require('moment');
var upload = multer({ dest: './public/upload/temp' });
module.exports = function(app) {
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);

app.post('/public/upload/temp', upload.single('img'), function(req, res) {
    //var form_description = req.body.description;
    console.log(req.file.name);
    //  insert operations into database get placed here
    res.redirect('/');
});

app.use('/public/', express.static(path.join(__dirname,
    '../public')));

if ('development' === app.get('env')) {
    app.use(errorHandler());
}

app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: app.get('views') + '/partials',
    helpers: {
        timeago: function(timestamp) {
            return moment(timestamp).startOf('minute').fromNow();
        }
    }
}).engine);
return app;
};

Following that, we have the Handlebar (HTML) file:

...

Lastly, here is the image.js Controller File

...

During server execution and attempting to upload an image by clicking the Upload Image button, I encounter the error:

Cannot read property 'path' of undefined

...

I have exhaustively scoured the internet for solutions but to no avail! If anyone can provide assistance, it would be greatly appreciated!

Answer №1

Perhaps the reason is that you included a semicolon (;) at the end of the error handler declaration

errorHandler = require('errorhandler');

Furthermore, ensure that in your HTML, the name attribute should be set to "img" if you are using multer.

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

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

The printing code is not able to interpret the CSS

Having trouble with this script not reading the style properly when printing, can anyone assist in identifying the issue? <script type="text/javascript"> $(function () { $("#btnPrint").click(function () { var contents = $( ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

Setting up Cypress's Electron browser for managing downloads

Is it possible to modify the Electron browser's configuration from within Cypress, in order to fix issues like download prompts not being detected? There is an issue with Cypress where it cannot detect download prompts, but there seems to be a potent ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

A guide on converting TypeScript to JavaScript while utilizing top-level await

Exploring the capabilities of top-level await introduced with TypeScript 3.8 in a NodeJS setting. Here's an example of TypeScript code utilizing this feature: import { getDoctorsPage } from "./utils/axios.provider"; const page = await getDo ...

AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly: categorieFilter = angular.module("categorieFilter", []) categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){ $scope.search = ""; $scope.products = []; $ ...

Using app.js in a blade file can cause jQuery functions and libraries to malfunction

In my Laravel application, I am facing an issue with my vue.js component of Pusher notification system and the installation of tinymce for blog posts. Adding js/app.js in my main layout blade file causes my tinymce and other jQuery functions to stop workin ...

Saving this object in Mongodb - here's how it's done

click here for imageCan you provide guidance on creating a schema and saving API data for this specific object in MongoDB? I am looking to store the information related to 'btcinr' as it will be fetched from an external API. Below is the sample ...

What is the method for parsing FormData() data in nodejs?

When sending a base64 image to the server side using FormData(), the response received may look something like this: {"------WebKitFormBoundaryjJtrF2zdTOFuHmYM\\r\\nContent-Disposition: form-data; name":"\\" ...

NodeJS QR code scanning with RaspberryPi camera

I'm working on a project to develop a nodeJS application that can scan QR codes using the Raspberry Pi3 board. I've been able to successfully implement this functionality with a USB camera using the Instascan node module. However, when attempting ...

How can one effectively extract data from a database in a React application?

We have a basic react app with authorization, utilizing JWT tokens and Redux for state management. Personally, I find the code quite complex and obfuscated, making it challenging to grasp fully. However, let's set that aside. Upon login, a token is s ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

React Router relies on a DOM for Browser History to function properly

I am currently developing my app using React.js and express. My main focus right now is setting up react-router-dom for the application. Unfortunately, I encountered a warning when attempting to run the app: Invariant Violation: Browser history needs a ...

AngularJS - Greetings global

Currently experimenting with AngularJS, however I noticed that the official tutorial provides download code and predefined npm dependencies without explaining how to create it from scratch. I am using Linux (Mint Mate 17) with Node.js / npm / bower instal ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Guide on setting up a connection to Hyperledger Fabric Gateway Service (recently introduced in HF 2.4) while ensuring TLS is enabled

My Hyperledger Fabric network setup is functioning well, except when I attempt to utilize the new Fabric-Gateway SDK (). I recently upgraded my network from version 2.3.1 to 2.4.1 and wanted to experiment with the new SDK, but I am encountering connection ...