Node.js / Express表单post req.body not working

时间:2011-09-22 22:05:03

标签: post node.js express

我正在使用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属性,也会发生这种情况

......我有什么遗漏/做错了吗?

我正在使用节点v0.4.11并表达v2.4.6

2 个答案:

答案 0 :(得分:36)

<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属性的所有表单控件的键/值哈希值,值是控件的值。

您需要为所有输入命名。

答案 1 :(得分:4)

这也是由于内容类型。请参阅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检查内容类型(req.is('json'))// return true / false

我认为'charset = UTF-8'在上面可以忽略不计。

相关问题