2011-09-22 147 views
25

我使用express並無法從bodyParser獲取表單數據。無論我做什麼,它總是作爲一個空虛的對象出現。這裏是我的快遞產生app.js代碼(我說的唯一的事情是在底部的app.post路線):Node.js/Express表單發佈req.body無法正常工作

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

回答

33

一個HTTP柱的主體是具有name屬性中的所有表單控件的鍵/值的散列,並且該值是控制的價值。

您需要爲所有輸入提供名稱。

+0

謝謝!不知道我是如何忽視的... – binarymax

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'))//返回真/假

我想 '的charset = UTF-8' 是在上述的可以忽略不計。