2012-02-19 153 views
4

我嘗試了很多財產 '標題' 弄清楚爲什麼這引發了這樣的錯誤:Expressjs POST錯誤:類型錯誤:無法讀取的不確定

Configuring 
Listening on 2000 
TypeError: Cannot read property 'title' of undefined 
    at /home/abdulsattar/learning/node/express/index.js:9:20 

的index.js:

var express = require("express"), 
    app = express.createServer(); 

app.get("/", function(req, res) { 
    res.send('<form action="/new" method="post"><input type="text" name="title" /><input type="submit" /></form>'); 
}); 

app.post("/new", function(req, res) { 
    res.send(req.body.title); 
}); 

app.configure(function() { 
    console.log("Configuring"); 
    app.use(express.bodyParser()); 
}); 

var port = process.env.PORT || 2000; 

app.listen(port, function() { 
    console.log("Listening on " + port); 
}); 

我已經讀過快遞需要bodyParser()。我在use以上,但它總是失敗。我在版本2.5.82.5.8(認爲可能是問題)上嘗試過,但兩個版本均失敗。有什麼我失蹤?

回答

11

我的預感,嘗試移動你的app.configure語句之前你的app.get和app.post。 bodyParser中間件沒有被調用。此外,爲了安全起見,將enctype添加到表單中,不應該有必要,但不管:application/x-www-form-urlencoded

讓我知道...

+1

哦,夥計!就是這樣!我在處理程序之前移動了configure語句,並且它工作正常。非常感謝! – 2012-02-19 10:58:59

相關問題