2013-12-20 46 views
2

我有一個使用express框架的node.js服務器。使用Node.js和Express框架無法讀取帖子參數

var express = require('express'); 
var http = require('http'); 
var api_helper = require('./helpers/api_helper'); 
var app = express(); 

app.use(app.router); 
app.use(express.bodyParser()); 
app.set('port', process.env.PORT || 8081); 

app.post('/api/nodev1/users/login', function(req, res){ 
    var email = req.param('email', null); 
    var password = req.param('password', null); 
    console.log(email);console.log(password); 
}); 

http.createServer(app).listen(app.get('port'), function(){ 
    console.log('Express server listening on port ' + app.get('port')); 
}); 

當我嘗試發送請求到/ api/nodev1/users/login時,我無法讀取參數。我正在嘗試使用curl如下:

curl -d "[email protected]" -d "password=mypassword" http://localhost:8081/api/nodev1/users/login 

電子郵件和密碼未定義。

+1

你在那裏有一個錯字。第12行應該是'var password = req.param('password',null);' –

+0

感謝您的錯字Joe。固定。它仍然不能解決我的問題:) – Tony

回答

7

您必須移動app.use(app.router)低於app.use(express.bodyParser())app.router只是一個處理你的路線的舞臺。如果它在bodyParser之前發生,則不會分析正文。

您的代碼看起來是這樣的(如果我沒能解釋可以理解):

var app = express(); 

app.use(express.bodyParser()); 
app.set('port', process.env.PORT || 8081); 

app.use(app.router); 

// I added following line so you can better see what happens 
app.use(express.logger('dev')); 

app.post('/api/nodev1/users/login', function(req, res){ ... } 

Offtopic句話express.bodyParser()當你有文件上傳,才應使用。然後你必須照顧刪除臨時文件。如果你沒有文件上傳,你最好只用

app.use(express.json()); 
app.use(express.urlencoded()); 

我只是想補充一點,如果你不知道。我跑的問題,因爲我不知道......

編輯爲Express 4的

感謝@喬納森翁有因爲快遞4無app.use(app.router)

All routing methods will be added in the order in which they appear. You should not do app.use(app.router) . This eliminates the most common issue with Express.

In other words, mixing app.use() and app[VERB]() will work exactly in the order in which they are called.

Read more: New features in 4.x

+0

我不希望參數通過網址傳遞,我希望他們在請求的身體 – Tony

+0

它是身體。您應該看到該URL僅在您的Express-log中登錄。 – hgoebl

+0

你想如何發佈這些值?它是一個HTML表單嗎?或者它應該是一個REST api並且你想發送JSON? – hgoebl

0

編輯 - 不,請參閱有關中間件訂單的其他答案!


變化req.paramreq.body.x

app.post('/api/nodev1/users/login', function(req, res){ 
    var email = req.param('email', null); 
    var password = req.param('password', null); 
    console.log(email);console.log(password); 
}); 

app.post('/api/nodev1/users/login', function(req, res){ 
    var email = req.body.email); 
    var password = req.body.password); 
    console.log(email); console.log(password); 
}); 
+0

這是一回事。函數'param'依次查找'req.params','req.body'和'req.query'。 [來源](https://github.com/visionmedia/express/blob/master/lib/request.js#L286) –

+0

好的謝謝。請注意鏈接的源在[行276](https://github.com/visionmedia/express/blob/master/lib/request.js#L276)上說'req.body'必須是一個對象。它可能不是沒有'app.use(express.bodyParser())'的對象 – Plato

相關問題