如何使用 POST , GET 在 Nodejs 中制作搜索框

Posted

技术标签:

【中文标题】如何使用 POST , GET 在 Nodejs 中制作搜索框【英文标题】:How to use POST , GET for making search-box in Nodejs 【发布时间】:2016-12-21 04:00:23 【问题描述】:

我想发布并从表单值中获取 getparameter 关键字并使用此查询

SELECT * from cider.cid_contents 
where con_content like \'%'+ keyword +'%\' 
order by con_no desc;

但我不知道如何从 post 或 form 方法中获取关键字值。 有代码

搜索.js

var express = require('express');
var router = express.Router();
var mysql = require("./model/mysql");

/* GET home page. */
router.post('/search/process', function(req, res, next) 

    var keyword = req.body.keyword;

    console.log(keyword);

    res.redirect('/search');


  );

router.get('/search/:keyword', function(req, res, next) 
    var keyword;
    keyword = req.params.keyword;
    console.log("+++++");
    console.log(keyword+"1234");
    mysql.select('SELECT * from cider.cid_contents where con_content like \'%'+ keyword +'%\' order by con_no desc;',


    function (err, data)
        if (err) throw err;

    res.render('front/search/search',  contents : data);
  );
);


module.exports = router;

这是一个表单标签(top.ejs)

<form action="/search/process" method="post">
                <input type="text" class="form-control web-search-box" placeholder="search" name="keyword" value=''></div>
                <div id="search" class="search col-sm-1"><img src="../../page_imgs/fixed_img/icon_search.png"></div>
                <input type="submit" value="send">
                </form>

/搜索 (search.ejs)

<table class="bordered">
        <thead>
          <tr>
              <th data-field="no">num</th>
              <th data-field="title">title</th>
              <th data-field="date">date</th>
              <th data-field="viewCount">count</th>
              <th data-field=""></th>
          </tr>
        </thead>
        <tbody>

        <% for(var i = 0; i<contents.length; i++)  %>
            <tr>

                <td><%= contents[i].con_no %></td>
                <td><a href="/adm/contents/detail/<%= contents[i].con_no %>"><%= contents[i].con_title %></a></td>
                <td><%= contents[i].con_regDate %></td>
                <td><%= contents[i].con_viewCount %></td>
                <td><a href="/adm/contents/delete/<%= contents[i].con_no %>">delete</a></td>
            </tr>
        <%  %> 
        </tbody>
      </table>

【问题讨论】:

【参考方案1】:

使用正文解析器。

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded(extended: true));

router.post('/search/process', function(req, res, next) 

  console.log(req.body);

);

有关示例,请参阅 https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters#post-parameters。

【讨论】:

以上是关于如何使用 POST , GET 在 Nodejs 中制作搜索框的主要内容,如果未能解决你的问题,请参考以下文章

如何通过nodejs中的get请求使用req.body

如何在 NodeJS 中维护请求会话

如何使用 REST/JSON/GET/POST 从我的节点服务器访问我的 couchdb?

NodeJS Express - 幕后GET / POST / PATCH / DELETE之间的区别

NodeJS获取GET和POST请求

nodejs 如何快速的遍历大量的文件夹