2011-09-22 6 views
25

Tôi đang sử dụng express và gặp sự cố khi nhận dữ liệu biểu mẫu từ bodyParser. Không có vấn đề gì tôi làm nó luôn luôn đi lên như một đối tượng trống rỗng. Dưới đây là rõ ràng tôi tạo app.js mã (điều duy nhất tôi nói thêm là con đường app.post ở phía dưới):Node.js/Express form post req.body không hoạt động

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); 

Dưới đây là hình thức HTML của tôi:

<!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> 

Khi tôi nộp hình thức, req.body là một đối tượng rỗng {}

giá trị của nó lưu ý rằng điều này xảy ra ngay cả khi tôi loại bỏ các thuộc tính enctype từ thẻ hình thức

... có một cái gì đó tôi đang thiếu/làm sai?

Tôi đang sử dụng v0.4.11 nút và nhanh v2.4.6

Trả lời

33

Phần nội dung của một bài HTTP là một hash key/value của tất cả các hình thức kiểm soát với một thuộc tính name, và giá trị là giá trị của điều khiển.

Bạn cần đặt tên cho tất cả các yếu tố đầu vào của mình.

+0

Cảm ơn bạn! Không chắc tôi đã bỏ qua điều đó ... – binarymax

4

Nó cũng do loại nội dung. vui lòng xem đối tượng console.log (req).

'content-type': 'application/json; charset=UTF-8’ // valid. 

'content-type': 'application/JSON; charset=UTF-8’ // invalid & req.body would empty object {}. 

Để kiểm tra kiểu nội dung bởi console.log (req.is ('json')) // trở lại đúng/sai

Tôi nghĩ 'charset = UTF-8' là không đáng kể ở trên.