2015-10-03 30 views
0

我正在構建一個Express查詢Twitter API v1.1的搜索引擎應用程序。目前,我正在嘗試通過使用bodyParser模塊解析表單數據來將搜索字符串提交給我的服務器。下面是代碼:在Express中使用bodyParser.text()與EJS

index.ejs

... 
<form method="GET" action="/results"> 
    <input id="input" type="text" name="search"> 
    <button id="searchButton">+</button> 
</form> 
... 

server.js

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

var app = express(); 

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

app.set('view engine', 'ejs'); 

app.use(express.static(__dirname + "/public"); 

var urlencodedParser = bodyParser.urlencoded({ extended: false }) 

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

app.get('/results', urlencodedParser, function (req, res) { 
    console.log(req.body); 
    res.render('results') 
}); 

app.listen(port, function() { 
    console.log('Our app is running on http://localhost:' + port); 
}); 

所示將返回{}到控制檯的代碼。如果我嘗試訪問req.body.search,它將返回undefined(顯然)。這裏有什麼問題?爲什麼它不記錄我的搜索字符串?

回答

0

您正在使用錯誤的車身解碼器。如果您要提交表單(application/x-www-form-urlencoded是表單的默認enctype),則需要bodyParser.urlencoded()而不是bodyParser.text()。後者用於明文請求數據,而不是表單數據。

此外,您還應該使用method="POST"POST路線(app.post('/results', ...)),而不是method="GET"GET路線。由於GET請求幾乎從不具有主體,因此瀏覽器會將表單數據轉換爲查詢字符串,然後將查詢字符串附加到網址本身。這意味着您的表單數據當前位於req.query而不是req.body。切換到POST雖然會導致瀏覽器發送請求正文中的表單數據,並且表單數據將按照預期在req.body中。

+0

沒有什麼區別。甚至切換到'enctype =「text/plain」'並保持_js_文件相同。 – Justin

+0

你不想爲表單使用「text/plain」。我已經更新了我的答案,以便在此處解釋附加問題。 – mscdex

+0

這樣就解決了這個問題。現在,當我用'heroku local web'運行服務器時,它會附加一個「?」在最後和301的,但如果我使用'節點server.js'它運行順利。對此有何想法?注意:我的_Procfile_表示'web:node server.js'。 – Justin