bodyParser.text() 在 Express with EJS 中的用法

Usage of bodyParser.text() in Express with EJS

我正在使用 Express 构建一个搜索引擎应用程序来查询 Twitter API v1.1。目前,我正在尝试通过使用 bodyParser 模块解析表单数据来将搜索字符串提交到我的服务器。这是代码:

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);
});

显示的代码将 return { } 发送到控制台。如果我尝试访问 req.body.search 它 returns undefined (显然)。这里的问题是什么?为什么它不记录我的搜索字符串?

您使用了错误的正文解码器。如果您要提交表单(application/x-www-form-urlencoded 是默认的 enctype 表单),您将需要 bodyParser.urlencoded() 而不是 bodyParser.text()。后者是明文请求数据,不是表单数据。

此外,您还应该使用 method="POST"POST 路线 (app.post('/results', ...)) 而不是 method="GET"GET 路线。由于 GET 请求几乎没有主体,因此浏览器将表单数据转换为查询字符串,然后将其附加到 url 本身。这意味着您的表单数据当前位于 req.query 而不是 req.body。切换到 POST 虽然会导致浏览器在请求正文中发送表单数据,并且表单数据将按预期在 req.body 中。