Node.js/Express 表单 post req.body 不起作用 [英] Node.js/Express form post req.body not working
问题描述
我正在使用 express 并且无法从 bodyParser 获取表单数据.无论我做什么,它总是作为一个空对象出现.这是我快速生成的 app.js 代码(我唯一添加的是底部的 app.post 路由):
I'm using express and having trouble getting form data from the bodyParser. No matter what I do it always comes up as an empty object. Here is my express generated app.js code (the only thing I added was the app.post route at the bottom):
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 表单:
Here is my HTML form:
<!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 是一个空对象 {}
When I submit the form, req.body is an empty object {}
值得注意的是,即使我从表单标签中删除了 enctype 属性,也会发生这种情况
Its worth noting that this happens even if I remove the enctype attribute from the form tag
...我有什么遗漏/做错了吗?
...Is there something I am missing/doing wrong?
我正在使用 node v0.4.11 和 express v2.4.6
I am using node v0.4.11 and express 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 帖子的正文是所有具有 name
属性的表单控件的键/值哈希,值是控件的值.
The body of a HTTP post is a key/value hash of all the form controls with a name
attribute, and the value is the value of the control.
您需要为所有输入命名.
You need to give names to all your inputs.
这篇关于Node.js/Express 表单 post req.body 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!