2014-11-05 125 views
0

我已經設置如下一個簡單的HTML表單:無法從HTML表單數據發送到節點服務器

<!doctype html> 
<html> 
    <head> 
     <title>Testing Echo server</title> 
    </head> 
    <body> 
     <form method="post" action="/"> 
      <input type="text" id="keyword" name="keyword" /> 
      <input type="submit" value="echo" id="submit" /> 
     </form> 
    </body> 
</html> 

我app.js看起來是這樣的:

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

app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html'); 
}); 

app.post('/', function (req, res) { 

     console.log(req.params); // logged as {} 
     res.writeHead(200); 
     //req.pipe(res);  // throws error 
     res.write('abc');  // works 
     res.end(); 

}); 

app.listen(8080); 

我無法訪問參數從表單發送。

我該如何解決這個問題?

+0

該路由本身不包含任何參數,所以如何在cosole中預期參數。如果你試圖獲得表單數據,你應該使用req.body – Amitesh 2014-11-05 09:47:35

+0

'req.body'給我'undefined'。 – 2014-11-05 09:51:21

+0

您需要安裝類似body-parser的解析器模塊(https://github.com/expressjs/body-parser)。爲了使您的開發更容易,請安裝節點檢查器來調試節點服務器。 – Amitesh 2014-11-05 10:00:28

回答

1

首先,如果你不想自己從http頭中取出數據,你需要body-parser middleware

那麼你不需要訪問參數,因爲你沒有任何,但請求的主體與req.body