Encountered an issue with using multer as middleware in Express 4

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

const uploadFile = multer({
  dest: __dirname + '../public/uploads/'
})

router.post('/upload', uploadFile, function(req, res) {
    console.log('File uploaded successfully');
})

I encountered an error message stating

Route.post() requires callback functions
after trying to follow a tutorial on uploading photos. Could this be due to a newer version of Express being used? I recall the way middleware is added to a route as shown above, but for some reason it doesn't seem to work here.

Answer №1

According to the information provided on the multer documentation, it appears that utilizing either uploading.single() or uploading.array() as your middleware is necessary. Here is a sample extracted from the demonstration in the multer documentation:

var upload = multer({ dest: 'uploads/' })

app.post('/profile', upload.single('avatar'), function (req, res, next) {
    // req.file will contain the `avatar` file 
    // req.body will store any text fields present 
}) 

Answer №2

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

const uploader = multer({
  dest: __dirname + '../public/uploads/',
})
const fileType = uploader.single('file');

router.post('/upload', fileType, function(req, res) {
    console.log('file has been uploaded successfully');
})

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

What is the best method for displaying data on the user interface in Angular after retrieving it from a CSV file

I am currently working on implementing an Angular template where I need to display data from a CSV file in a structured table format. However, I am facing challenges with the core scripting part related to the retrieved CSV data. Here is a snippet of my c ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

Developing an ASP.NET application that returns a custom object in JSON format

I have a class called CodeWithMessage that I need to return as a json object from my web service. Here is how the class is defined: namespace UserSite //Classes For my site { namespace General { public class CodeWithMessage { ...

Converting blobs to strings and vice versa in Javascript

After successfully converting a blob to a string using FileReader, the challenge now is to convert it back: var reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { base64data = reader.result; var blobToSend ...

a code translator for running compiled programs

I'm curious about executing Windows or GNU/Linux programs directly from a webpage. This is not related to any type of Remote Desktop functionality. My vision involves a user opening a webpage that includes a concealed file containing executable code o ...

Incorporating website data into my JavaScript code

I lack experience in extracting data from websites, but I'm interested in learning how to utilize data from: . I believe this data is in the form of an array and I want to loop through it to find an item with the name "example" and gather additional i ...

PHP script is not successfully receiving the Ajax post request that is

As a newcomer to the world of php and ajax, I am facing a challenge in passing a variable from jquery to a php page loaded within a modal window. My php script fetches table information for multiple users. Next to each user's name, there is an edit b ...

When using body-parser, req.body may sometimes unexpectedly return undefined

My current project involves creating an API that handles POST requests for user creation. Unfortunately, I'm encountering undefined errors for all the req.body calls. Here's a simplified overview of how my application is structured: User control ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

Insert a div element into the JavaScript file

I have a JavaScript code snippet that needs to be inserted after the "Artwork" section. Here is the code: <div class="image-upload"> <label for="files"> <img src="ohtupload.jpg"> </label> </di ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Is there a way to stop the dropdown menu from disappearing when clicking on a popover that was activated from the dropdown?

Are you familiar with creating a popover that is triggered by a dropdown menu using the Twitter Bootstrap javascript components? Could you provide guidance on how to prevent the dropdown menu from closing when a user clicks on the popover? For reference, ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...

Utilizing correct Django CSRF validation when making a fetch post request

I've been experimenting with JavaScript's fetch library to perform a form submission on my Django application. Despite my efforts, I keep running into CSRF validation issues. The Ajax documentation suggests specifying a header, which I have atte ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

What is the proper way to incorporate CSS files for API routes in Express?

Utilizing express and handlebars has presented an issue for me. The pages with URLs like http://localhost:5000/api/posts are not loading CSS files properly. However, URLs such as http://localhost:5000 or http://localhost:5000/register function correctly. ...

When you click on links and buttons, a focus outline appears

I am currently troubleshooting an issue within an existing application that relies on the use of jQuery. The problem arises when I click on any link or button on the page, causing the element to display a focus outline (such as a blue glow in browsers like ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

What is the recursive process for printing the numbers 1 to 5 and then 5 to 1?

I was looking to print numbers from 5 to 0 and then from 0 to 5 in the most concise way possible. The code I came up with is below. However, I am open to other suggestions that may require fewer lines of code. Looking forward to your feedback. Thanks! ...