Jazzy
Jazzy

Reputation: 6129

Why is this Express middleware not being called with arguments?

I am working on a middleware that needs bodyParser to run, but I don't want to make the app bring that in as a dependency. Instead, I want to make a package that requires that and exports a middleware like this:

//routes.js
app.use('/', middlewareWrapper(thing));

//middlware.js
export function middlewareWrapper(thing) {
    return function addBody(req, res, next) {
        function othermiddleware(_req, _res) {
            // do something with thing and _req
            return next();
        }
        return bodyParser.json()(req, res, othermiddleware);
    };
}

This looks like it would work, and the othermiddleware is called, but with no arguments.

I found another answer that addresses this in basically the same way (it's old, but JS still works the same way): https://stackoverflow.com/a/17997640/444871

Why is the othermiddleware being called with no args?

Upvotes: 0

Views: 332

Answers (2)

Prakash Sharma
Prakash Sharma

Reputation: 16472

The problem is that the middleware returned by bodyParser.json() simply call next() like this (i.e. with no argument). Here you are passing othermiddleware as next to the middleware returned by bodyParser.json(). Therefore it does not contain any argument.

Also the bodyParser does not change the original reference of req/res object. So the main req/res object still refer to the same object. So you dont need arguments to be passed. You can simply use the same req/res object in your othermiddleware function too.

return function addBody(req, res, next) {
        function othermiddleware() {
            // You should be able to use req and res modified by bodyParser.
            // You dont need arguments to be passed.
            return next();
        }
        return bodyParser.json()(req, res, othermiddleware);
    };

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138235

Cause you do

next();

without passing parameters. Usually express does sth like that:

bodyParser.json()(
  req,
  res,
  () => {
    othermiddleware(req,res,next);
  }
);

Or you use some bind magic:

bodyParser.json()(req, res, othermiddleware.bind(this,req,res,next));

Upvotes: 1

Related Questions