我正在使用 express,但无法从 bodyParser 获取表单数据。无论我做什么,它总是作为一个空对象出现。这是我快速生成的 app.js 代码(我唯一添加的是底部的 app.post 路由):
var express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
res.sendfile('./public/index.html');
});
app.post('/', function(req, res){
console.log(req.body);
res.sendfile('./public/index.html');
});
app.listen(3010);
这是我的 HTML 表单:
<!doctype html>
<html>
<body>
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
当我提交表单时,req.body 是一个空对象 {}
值得注意的是,即使我从表单标签中删除 enctype 属性也会发生这种情况
...我有什么遗漏/做错了吗?
我正在使用 Node v0.4.11 并表示 v2.4.6
最佳答案
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="I_appear_in_req_body" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
HTTP post 的正文是所有具有 name
属性的表单控件的键/值哈希,值是控件的值。
您需要为所有输入命名。
关于post - Node.js/Express 表单发布 req.body 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7522034/