在节点express中请求body undefined

在节点expression式中,当我尝试从窗体访问post值时,它显示请求体未​​定义的错误。 这是我的代码,

http.createServer(function(req, res) { var hostname = req.headers.host.split(":")[0]; var pathname = url.parse(req.url).pathname; if (pathname==="/login" && req.method ==="POST") { console.log("request Header==>" + req.body.username ); }).listen(9000, function() { console.log('http://localhost:9000'); }); 

请任何人帮我find为什么请求正文显示未定义。

如果你不使用express的networking服务器,只是普通的http。 使用车身模块。

首先启用身体分析器中间件

 var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:\n') res.end(JSON.stringify(req.body, null, 2)) })