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?

4

1 回答 1

1

我不确定这是否会起作用以及它是否会一直起作用,但我相信这将是做你想做的事情的“更接近”的方式,而不依赖于连接/表达(你没有指定的东西在你的问题中)。

// 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 );
    }
}
于 2013-08-01T15:01:43.923 回答