Node.js / Express表单post req.body不工作
我正在使用快递,无法从bodyParser获取表单数据。 无论我做什么,它总是作为一个空虚的对象出现。 这里是我生成的app.js代码(我添加的唯一东西是app.postpath在底部):
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属性,也会发生这种情况
…有什么我失踪/做错了吗?
我正在使用节点v0.4.11和expressionv2.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>
HTTPpost的主体是具有name
属性的所有表单控件的键/值散列,值是控件的值。
你需要给所有的input名称。
这也是由于内容types。 请参阅console.log(req)对象。
'content-type': 'application/json; charset=UTF-8' // valid. 'content-type': 'application/JSON; charset=UTF-8' // invalid & req.body would empty object {}.
通过console.log检查内容types(req.is('json'))//返回true / false
上面我认为'charset = UTF-8'可以忽略不计。