Express js的身体parsing器不工作?
我在我的节点服务器中使用快递以下(截断到重要的部分):
var app = express.createServer(); app.all(/test/,function(req,res){ console.log(req.headers); console.log(req.body); res.send(""); }); function appStart(cobrands){ app.configure(function(){ app.use(express.bodyParser()); app.use(express.cookieParser()); app.use('/min',express.static('../min')); app.use('/js',express.static('../js')); app.use('/css',express.static('../css')); app.use('/img',express.static('../img')); }); app.listen(8080); }
然后我有一个简单的表单调用localhost:8080像这样:
<form action="http://localhost:8080/test" method="post"> <input type="hidden" name="test" value="testing"/> <input type="submit" name="submit" value="to node"/> </form>
但express.bodyParser似乎没有做任何事情,而且req.body是未定义的。 以下是console.log
的输出:
// req.headers { host: 'localhost:8080', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/534.48.3 (KHTML, like Gecko) Version/5.1 Safari/534.48.3', 'content-length': '27', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', origin: 'file://', 'content-type': 'application/x-www-form-urlencoded', 'accept-language': 'en-us', 'accept-encoding': 'gzip, deflate', cookie: '', connection: 'keep-alive' } // req.body undefined
注意: content-type
被正确地定义为application/x-www-form-urlencoded
因为它应该是bodyParser的工作,我已经validation它是通过在Safari中打开debugging工具并validation表单数据存在。
http://expressjs.com/guide.html#configuration
请注意使用app.router,它可以(可选地)用来挂载应用程序路由,否则第一次调用app.get(),app.post()等会挂载路由。
在添加任何其他中间件之前,你正在调用app.all()。 这样做有效地把app.router放在所有其他中间件的前面,导致它们永远不会用在你的路由中的请求上。
挂载应用程序的路线与app.use(app.router);
非常相似app.use(app.router);
。
最后你的堆栈是这样的:
app.use(app.router); // Contains your /test/ route app.use(express.bodyParser()); app.use(express.cookieParser()); app.use('/min',express.static('../min')); app.use('/js',express.static('../js')); app.use('/css',express.static('../css')); app.use('/img',express.static('../img'));
tl; dr在你的调用app.configure()和app.listen()之间移动你的路由。
我有类似的问题,我发现这是因为破/缺lessexpress.bodyParser()。 相反,express的bodyParser我已经使用connect的bodyParser,它的工作就像一个魅力:
app.use(require('connect').bodyParser());