使用 GET 请求传递 HTML 值
Passing HTML values using GET request
我正在尝试通过 GET 请求将 HTML 表单元素值传递到 node.js 文件中。
我该怎么做?
我在 POST 请求中找到了类似的例子,但我需要在这里单独使用 GET 请求。
HTML 表单值是我将用于在数据库中搜索的搜索字符串。
app.get('/search', function (req, res){
res.sendfile('./views/search.html');
console.log(req.body.denomination);
user.find({denomination: req.params.denomination}, function (err, docs) {
res.render('index', {users: docs});
});
});
<form action="/search" method="get">
<label for="denomination">Denomination</label><br>
<input type="text" name="denomination"><br>
<button type="button" class="btn btn-primary btn-lg" onclick="like(this)">submit</button>
</form>
要在 GET 请求后获取值,您可以使用 req.query.<your_html_field>
。
此外,请检查您是否已设置 app.use(bodyParser.urlencoded({ extended: true }));
以允许您搜索 querystring
。您可以找到更多信息 here.
我不确定你的方法开头的 res.sendfile(...)
,它是否已经发送响应,但我认为它在工作。
只需对您的路线进行以下两个小改动:
app.get('/search', function (req, res){
res.sendfile('./views/search.html');
// Changed here from `body` to `query`
console.log(req.query.denomination);
// Changed here from `params` to `query`
user.find({denomination: req.query.denomination}, function (err, docs){
res.render('index', {users: docs});
});
});
希望对您有所帮助。
我正在尝试通过 GET 请求将 HTML 表单元素值传递到 node.js 文件中。
我该怎么做?
我在 POST 请求中找到了类似的例子,但我需要在这里单独使用 GET 请求。 HTML 表单值是我将用于在数据库中搜索的搜索字符串。
app.get('/search', function (req, res){
res.sendfile('./views/search.html');
console.log(req.body.denomination);
user.find({denomination: req.params.denomination}, function (err, docs) {
res.render('index', {users: docs});
});
});
<form action="/search" method="get">
<label for="denomination">Denomination</label><br>
<input type="text" name="denomination"><br>
<button type="button" class="btn btn-primary btn-lg" onclick="like(this)">submit</button>
</form>
要在 GET 请求后获取值,您可以使用 req.query.<your_html_field>
。
此外,请检查您是否已设置 app.use(bodyParser.urlencoded({ extended: true }));
以允许您搜索 querystring
。您可以找到更多信息 here.
我不确定你的方法开头的 res.sendfile(...)
,它是否已经发送响应,但我认为它在工作。
只需对您的路线进行以下两个小改动:
app.get('/search', function (req, res){
res.sendfile('./views/search.html');
// Changed here from `body` to `query`
console.log(req.query.denomination);
// Changed here from `params` to `query`
user.find({denomination: req.query.denomination}, function (err, docs){
res.render('index', {users: docs});
});
});
希望对您有所帮助。