我在我的Node服务器上使用Express有以下内容(仅列出重要部分):
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工作所必需的。我已经通过在Safari中打开调试工具并验证表单数据是否存在来验证它是否传输过来了。