简体   繁体   中英

Search Database | NodeJS, Express, HTML

I am trying to write a simple web application in node.js that will allow a user to enter data into a search bar and then send the input to the server which will query the database with the user generated input. I already have my database set up and connected, but here is my code:

SERVER

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>

Now I have all my routers and middleware setup in node, but I can't seem to figure out how to simply get the user input to send to the server. I tried using the 'req.query.key' to get the value of the search input but that actually returns as undefined in my case. So, is there anyway to actually recieve the text through the 'req.query.key' variable, also is there a more 'conventional' method of making a simple database search bar?

PS I am still very new to programming in Express and Node.js as a whole, so if you see any common mistakes or 'sloppy' code I'd love to hear your feedback.

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

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

You can try using npm body-parser, in place of req.params.key you can put req.body.input (where input is the name of the input element).

Put this:

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

Before your template engine configuration (before setting your views)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM