如何从中间件中调用{express,connect} .bodyParser()? [英] How do I call {express,connect}.bodyParser() from within middleware?
问题描述
我有一些自定义中间件。在我的某些处理程序中,我想使用 req.body
,但这仅在用户使用时有效
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());
我总是可以告诉用户必须先使用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.
有什么方法可以调用 express.bodyParser()$中间件中是c $ c>还是
connect.bodyParser()
?
Is there any way to invoke express.bodyParser()
or connect.bodyParser()
inside middleware?
推荐答案
我不确定这是否会奏效,是否会一直奏效,但我相信这将是您完成所需工作的更近一步方式,无需依赖于连接/表达 (您未在问题中指定的内容)。
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 );
}
}
这篇关于如何从中间件中调用{express,connect} .bodyParser()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!