2015-06-11 63 views
1

我正在開發nodejs項目。我在express-helpers模塊的幫助下使用ejs生成視圖模板html。如何獲得app.post中的post params

server.js文件

我已經寫了下面的代碼

var http = require('http'); 
var path = require('path'); 

var async = require('async'); 
var socketio = require('socket.io'); 
var express = require('express'); 


var app = express(); 

var helpers = require('express-helpers') 
helpers(app); 

var server = http.Server(app); 

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){ 
    var addr = server.address(); 
    console.log("Chat server listening at", addr.address + ":" + addr.port); 
}); 

app.use(express.static(__dirname + '/public')); 
app.set('views', __dirname + '/public/views'); 
app.engine('html', require('ejs').renderFile); 
app.set('view engine', 'html'); 

//app.use(express.static(__dirname + '/client')); 
app.use(express.static(path.join(__dirname, '/client'))); 

// respond with "index.html" when a GET request is made to the homepage 
app.get('/', function(req, res) { 
    res.render('index.html'); 
}); 

app.get('/demo', function (req, res) { 
    res.render('demo.ejs'); 
}); 

app.post('/demo', function (req, res) { 
     console.log(res.body) 
}); 

我想知道,在app.post應該如何id來獲取post數據

app.post('/demo', function (req, res) { 
     console.log(res.body) 
}); 

我已經試過console.log(req.body)但給人的undefined 也試過console.log(res.body)但作爲undefined

讓我知道我應該如何實現它?

回答

4

你應該使用中間件如body-parser

var bodyParser = require('body-parser'); 

app.use(bodyParser.json()); // for parsing application/json 
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded 

app.post('/demo', function (req, res) { 
    console.log(req.body) 
}); 
2

使用body-parser中間件。首先,您需要使用npm install body-parser進行安裝。然後在你的應用中使用它像這樣

var bodyParser = require('body-parser'); 
..... 

// For Content-Type application/json 
app.use(bodyParser.json()); 
// For x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true })); 

.... 

app.post('/demo', function (req, res) { 
    console.log(req.body); 
});