【问题标题】:Search Database | NodeJS, Express, HTML搜索数据库 | NodeJS,快递,HTML
【发布时间】:2017-01-27 05:45:56
【问题描述】:

我正在尝试在 node.js 中编写一个简单的 Web 应用程序,它允许用户在搜索栏中输入数据,然后将输入发送到服务器,服务器将使用用户生成的输入查询数据库。我已经设置并连接了我的数据库,但这是我的代码:

服务器

var express = require('express');
var sql = require('mysql');
var app = express();

//Configure application
app.set('views',__dirname + '/views'); //Set views directory
app.use(express.static(__dirname + '/JS'));
app.set('views engine', 'ejs'); //Set view engine to ejs
app.engine('html', require('ejs').renderFile);
app.use(function(req, res, next){ //Set no cache for the server
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.header('Expires', '-1');
  res.header('Pragma', 'no-cache');
  next();
})

//Connect to mySQL database
var db = sql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'homeDB'
});
db.connect(function(err){
  if(err){console.log('there was an error connecting to the database' + err);}
})

//Set up routers (request handlers)

//Return home page when root('/') is requsted
app.get('/', function(req, res){
  res.render('index.html');
});

app.get('/search', function(req, res){ //GET method to access DB and return results in JSON
  db.query('SELECT * FROM products WHERE product LIKE "%' + req.query.key + '%"',
  function(err, rows, fields){
    if(err) throw err;
    var data = [];
    for(i=0;i<rows.length;i++){
      data.push(rows[i].product);
    }
    res.end(JSON.stringify(data));
  });
});

app.get('/typeahead.bundle.js', function(req, res){ //When typeahead is requested, send it to client
var fileName = './typeahead.bundle.js';
  var options = {
    cacheControl: false,
    root: __dirname
  }
  res.sendFile(fileName, options, function(err){
    if(err){
      console.log('there was an error sending ' + fileName + err);
      res.status(err.status).end();
    }else{console.log('Sent! ' + fileName);}
  });
});

app.post('/search', function(req, res){ //POST method to access DB and return results in JSON
  db.query('SELECT * FROM products WHERE product LIKE "%' + req.params.input + '%"',
  function(err, rows, fields){
    if(err) throw err;
    var data = [];
    for(i=0;i<rows.length;i++){
      data.push(rows[i].product);
    }
    res.end(JSON.stringify(data));
    console.log(req.params.input);
  });
});

var server = app.listen(3000, function(){ //Start the server on port 3000
  console.log('server has started on localhost:3000...')
});

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Express Application</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="/typeahead.bundle.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>Thank you for connecting to my server!</h1>

    <form class="search" action="typeahead" method="post">
      <input class="form-control typeahead tt-query" type="text" name="input" placeholder="Search">
      <input class="btn btn-primary" type="submit" name="input" value="Submit">
    </form>

    <script type="text/javascript">
      $(document).ready(function(){
        $('input.typeahead').typeahead({
          name: 'typeahead',
          remote: 'http://localhost:3000/search?key=%QUERY',
          limit: 10
        });
      });
    </script>
  </body>
</html>

现在我在节点中设置了所有路由器和中间件,但我似乎无法弄清楚如何简单地将用户输入发送到服务器。我尝试使用“req.query.key”来获取搜索输入的值,但在我的情况下实际上返回为未定义。那么,到底有没有通过“req.query.key”变量实际接收文本,还有更“传统”的方法来制作简单的数据库搜索栏吗?

附:作为一个整体,我对使用 Express 和 Node.js 进行编程仍然很陌生,所以如果您发现任何常见错误或“草率”代码,我很想听听您的反馈。

【问题讨论】:

    标签: javascript ajax node.js express


    【解决方案1】:

    您可以尝试使用 npm body-parser 代替 req.params.key,您可以使用 req.body.input(其中 input 是输入元素的名称)。

    把这个:

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    

    在模板引擎配置之前(设置视图之前)

    【讨论】:

    • 这确实有效,查找了 body-parser 文档,进行了设置,我的应用程序现在正在从我的数据库中返回字段。谢谢!
    【解决方案2】:

    您是否尝试过通过以下方式获取参数

    var key = request.options.key || (request.options.where && request.options.where.key) || request.param('key');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多