2

I have some custom middleware. In some of my handlers, I want to use req.body, but that only works if the user did

app.use(express.bodyParser());

I could always tell the user, "you must use express.bodyParser() first," but I prefer to be safe and instantiate it if it has not been loaded yet.

Is there any way to invoke express.bodyParser() or connect.bodyParser() inside middleware?

deitch
  • 14,019
  • 14
  • 68
  • 96

1 Answers1

1

I'm not sure if this is will work and if it'll always work, but I believe it'll be the "closer" way of doing what you want, without depending on connect/express (thing that you haven't specified in your question).

// Beware that the main module of the node process _must_
// be able to resolve express with this! This will allow to not depend on express.
var express = require.main.require( "express" );

// If you can depend on express, use this instead!
//var express = require( "express" );

function yourMiddleware( req, res, next ) {
    var me = function( req, res ) {
        // do your things
        next();
    };

    if ( req.body === undefined ) {
        express.bodyParser()( req, res, me );
    } else {
        me( req, res );
    }
}
gustavohenke
  • 40,997
  • 14
  • 121
  • 129
  • Oh, nice. Why do you do require.main.require('express')? If you require('express'), it should always require the same first module. – deitch Aug 01 '13 at 17:42
  • Oh, wait I get it. So my own package doesn't need it. But it shouldn't matter. I can always do the following (see the edit) – deitch Aug 01 '13 at 17:43
  • A tip: add either express or connect as a `peerDependency`. It will require the package to be installed somewhere in your package tree. – gustavohenke Aug 03 '13 at 02:38