问题
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?
回答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 );
}
}
来源:https://stackoverflow.com/questions/17996948/how-do-i-call-express-connect-bodyparser-from-within-middleware