Exploring multipart uploads in Express JS 4: Leveraging body parser and dicer for efficient file handling

Currently, with express 4 and body-parser set up as shown below:

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

After integrating dicer, it seems like body parser functionality is affected. I am no longer able to access post parameters in req.params, req.body, or req.query.

I'm curious if there is a way to manually utilize body parser. Does body parser detect multipart forms data and take no action, assuming that another library will handle it?

It's worth mentioning that I have a specific reason for using dicer to parse the multipart form data and ideally would like to avoid switching to busboy, multer, or similar alternatives.

Answer №1

If you're wondering whether there is a manual way to utilize body-parser, the answer is yes and it's actually the recommended method of using it. According to the body-parser documentation:

Express Route-Specific

This example illustrates adding body parsers specifically to the routes that require them. Typically, this is considered the most advisable approach to integrating body-parser with express.

(I included some semi-colons because they bothered me until I did!)

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

// POST /login receives urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400);
  res.send('welcome, ' + req.body.username);
})

// POST /api/users receives JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400);
  // create user within req.body
})

Depending on which routes necessitate body-parser, you can implement it utilizing custom middleware. Now, I haven't personally tested this, but my assumption is that you could also integrate it in a similar manner as other express middleware:

// URL encoded bodies
app.use('/api/url/encoded/endpoint', bodyParser.urlencoded({ extended: false }));
// JSON encoded bodies
app.use('/api/json/encoded/endpoint', bodyParser.json());

Any routes matching the above endpoints, such as

app.use('/api/url/encoded/endpoint/test', function (req, res) { ... });

would be parsed using the appropriate middleware as long as they are declared below the middleware declarations in your code.

To address your entire inquiry, I would suggest attempting to not use either parser globally. Keep your parsers specific to API endpoints and you shouldn't encounter any issues.

Edit:

Your question is somewhat ambiguous. Are you looking to use body parser for multipart/form-data? "Body-parser does not handle multipart bodies, due to their complex and typically large nature." If that's the case, maybe consider trying out the bodyParser.raw({ type: ... }) function. Otherwise, you may need to utilize dicer within a custom middleware function where you verify the correct content type.

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

When manipulating an object in mongoose, encountering a loop is common

One of the routes in my nodejs API app looks like this: router.post('/startuserseries', function(req, res, next){ if(!req.body.username){ return res.status(400).json({message: 'Geen username'}); } User.findOne({ 'userna ...

Issue with res.redirect() function not working as expected

I've been tackling a Google OAuth flow using Express as the backend, and in a particular part of my code, I'm utilizing res.redirect(). Strangely, when I visit the route in my browser, it seems to have no effect whatsoever, not even triggering an ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

Setting up a Next.js app on IIS as a secondary sub application

I am looking to set up my Next.js application as a sub-application under an existing IIS website. Although I have successfully hosted the Next.js app as a standalone website, I need assistance in configuring it as a sub-app. The reason for this setup is th ...

Error: Failed to convert value "NaN" to ObjectId for the "_id" field

[ Issue resolved... the solution turned out to be surprisingly simple... $scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)}) .$promise.then( should have been: $scope.article = articleFactory.getArticles().get ...

Could the comments within a NodeJS script be causing memory problems?

I specialize in creating NodeJS libraries, and my coding practice includes adding JSDoc comments for documentation purposes. Here is an example of how my code usually looks: /** * Sum * Calculates the sum of two numbers. * * @name Sum * @function * ...

Issues with HTTPS in Puppeteer and VUE JS

I am encountering an issue when running tests from NODE net::ERR_CONNECTION_REFUSED at https://localhost:8087 at navigate (node_modules/puppeteer/src/common/FrameManager.ts:190:13) Test Suites: 2 failed, 2 total Tests: 7 failed, 7 total Snapshots: ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

The strategy for synchronizing API calls across multiple tabs in a browser

Can an API be called on multiple browser tabs simultaneously? For instance, in Tab A I make a call to the apple API with data A, and in Tab B I also call the same apple API but with data B. This means that the apple API in Tab A should ...

Cordova is having trouble locating the JAVA_HOME directory

Despite numerous attempts, I have yet to find a solution to my issue. I am in the process of developing a Cordova Android app, but consistently encounter failures with cordova requirements due to an inability to locate JAVA_HOME. The error message I receiv ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...

Encountering difficulties parsing XML using NodeJS (with ExpressJS) for MongoDB integration

I have a unique scenario where my data source is only available in XML format, whereas MongoDB prefers JSON. To work around this, I am attempting to adapt a method that currently handles JSON data to now process XML data instead. Below is the modified met ...

Is there a way to determine whether all fields in a schema have been populated or remain empty?

I am working with a schema that looks like this: How can I determine if all the fields in the schema have been filled or not? The front-end (React.js) includes an onboarding process where users who are logging in for the first time need to complete onboa ...

Controlling flow with Middleware in ExpressJS using Router.param() & Router.use()

Within my Express.js application, I have integrated custom validations and parameter parsing. Specifically, one of my routes requires the obj_id to be included in the route. In cases where mongoose cannot locate an object with that ID in the database, a 40 ...

Is there a way to identify the specific segment of code utilized when making an API call to a Node.js REST API?

Curious how to identify which part of a Node.js and Express.js REST API code is utilized during an API call? Looking for a way to view this information without manually analyzing the code line by line? ...

What methods can we use to determine if the TURN or STUN server has successfully established a connection?

I rely on http://code.google.com/p/rfc5766-turn-server/ for my TURN and STUN server setup. I'm looking to develop diagnostics to determine whether the STUN or TURN servers are connected. I would greatly appreciate any assistance with: 1) Implementi ...

Tips for displaying the contents of `[object Promise]` within koa2

I have a query let data = ctx.get("list.json"); ctx.set("Content-Type", "application/json"); await ctx.render('index', { somecontent:onecontent, seconddata: list }); In index.ejs &l ...

What steps do I need to take to ensure that User.findByIdAndUpdate is executed only after the new password has been successfully set?

My code is intended to allow users to change their passwords when they want, but it seems that the hashing of the new password isn't working as expected. The issue appears to be related to the asynchronous nature of promises in JavaScript, where the l ...