【问题标题】:Passing HTML values using GET request使用 GET 请求传递 HTML 值
【发布时间】:2016-11-02 07:28:07
【问题描述】:

我正在尝试通过 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>

【问题讨论】:

    标签: node.js get request query-string


    【解决方案1】:

    要在 GET 请求后获取值,您可以使用 req.query.&lt;your_html_field&gt;

    另外,检查您是否设置了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});
        });
    });
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 1970-01-01
      • 2016-04-17
      • 2019-09-07
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多