Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected.

In my Node.js + Express web application, I'm utilizing the BodyParser library to parse post parameters. However, I now require more control over multipart form-data POST requests as they are received - specifically, I need to stream the input directly to another server without having to download the whole file first.

All file uploads are currently being parsed automatically and made available using "request.files" before reaching any of my functions.

Is there a way for me to disable BodyParser only for multipart formdata posts without disabling it for other types of requests?

The structure of my app.js file involves defining an authentication route that doesn't expect files, just a token (POST parameter). There's also an upload route that accepts both files and POST parameters via form-data. This route is accessed only after authentication. Therefore, the issue arises where I want to disallow form-data in the authenticated route but allow it in the upload path. Essentially, I need BodyParser to function in the auth route while using Multer (another library) in the upload path to handle file parsing. As my real application has many more routes, I aim to code this efficiently with minimal redundancy.

var express = require('express');
var app = express();


var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));


var route_auth = require('./routes/auth');
app.use('/api/post/*', route_auth);
var route_upload = require('./routes/post/upload');
app.use('/api/post/upload', route_upload );


app.listen(3000, function() {
    console.log('Server listening on port 3000!')
});

The auth route implementation resembles the following:

router.post("/", function(req, res, next) {
       if(everythingiscool){
            return next()
        }
           next(err);
});

Meanwhile, the upload route is structured as shown below:

var express = require('express');
var router = express.Router();
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' });

router.post("/", upload.single('avatar'), function(req, res, next) {
         //work with req.file
});

Answer №1

To enhance the bodyParse middleware, create a function that verifies whether the request body's Content-Type is multipart or not:

var checkMultipart = /^multipart\//i;
var bodyParser = require('body-parser');
var urlencodedMiddleware = bodyParser.urlencoded({ extended: true });
app.use(function (req, res, next) {
  var type = req.get('Content-Type');
  if (checkMultipart.test(type)) return next();
  return urlencodedMiddleware(req, res, next);
});

Answer №2

Instead of turning off, how about turning on the middleware specifically for certain routes or routers?

For specific routes, you can include it as an additional parameter before your main route handler, like this:

app.get('/download', authenticationMiddleware, (req, res) => {
  // handle route logic here
});

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

Steps to ensure that MongoClient is accessible globally on all pages within a Node.js REST API

After researching the official MongoDB documentation, I have successfully integrated mongoDB into my NodeJS REST API using the following connection code. const { MongoClient } = require("mongodb"); // Connection URI const uri = "mongodb+s ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...

I am having trouble establishing a connection between two containers on Heroku

My web application is built using Node.js and MongoDB. After containerizing it with Docker, everything worked fine locally. However, when I tried to deploy it to production, I encountered an issue where the backend could not establish a connection with the ...

Testing events using mocha for unit testing

Are you uncertain about the best way to test this code using mocha and chai? module.exports = function trackCustomDyEvents(events){ let $; trackEvents(); function trackEvents() { events.forEach((event) => { $(document).on(event.type, even ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

Is there a way to detect when the user closes a tab or browser in HTML?

I am currently developing a web application using the MVC architecture and I need to find a way to detect when a user closes their browser tab so that I can destroy their session. My tech stack includes jsp (html, js) and java. Any suggestions on how to ...

Using JavaScript to toggle the display of a label element

Greetings everyone! I recently posted a question on this thread about replacing input with javascript, but ended up abandoning that idea. Instead, I decided to explore a different approach... I made the background of my password field transparent and posi ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Looking to navigate quickly from one section to the next on the page?

Is it possible to navigate within a single page using react-router-dom instead of rendering different components? I have my website content already rendered in 5 components, each covering 100vh. I am looking for a way to seamlessly jump from one section t ...

Tips for updating VUE's main.js file to incorporate the routers/index.js configuration

What is the reason for the difference in syntax between the VUE UI main.js code generated by CLI/3 and the older version, and how does it function? What are the various components of the new syntax and how do they work? sync(store, router) // for vuex-rou ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...

When using $resource.save, it returns a "Resource" instead of just an ID

For some reason, I am struggling with a seemingly simple task and cannot find a solution by going through documentation or other Angular related questions on SO. I may not be the brightest, so I could really use some help here as I am feeling stuck. Take ...

Experiencing issues with installing npm packages in a NativeScript project even after attempting to utilize nativescript-nodeify

Struggling with a persistent issue that has been causing me headaches for hours. I am currently developing a mobile app in a nativescript environment and need to decode JSON Web Tokens for login purposes. However, when trying to install the npm jsonwebtoke ...

Contrasting WebSQL and SQLite in terms of their utility in mobile applications and web browsers

Could you confirm if WebSQL and SQLite are the same? Are both WebSQL and SQLite available in PhoneGap? Will the JavaScript code used for WebSQL in a web browser be the same for a mobile app, or will we need different code? What advantages does WebSQL ha ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

Unable to produce scrolling animation using JavaScript

I'm trying to implement a feature on my website where the page scrolls with a sliding effect when the user presses the "Scroll" button. However, I've encountered issues as it doesn't seem to work despite adding the necessary tags to my HTML ...