私はnode.jsにユーザーが検索バーにデータを入力し、入力をサーバーに送信する単純なWebアプリケーションを作成しようとしています。 。私はすでにデータベースがセットアップされ、接続されているが、ここに私のコードされています。今、私は中に私のすべてのルータおよびミドルウェアを設定している検索データベース| NodeJS、Express、HTML
サーバ
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'変数を使ってテキストを受け取ることはありますか?また、単純なデータベース検索バーを作るための「従来の」方法がありますか?
P.S.私はまだExpressとNode.js全体でプログラミングするのが非常に新しいので、一般的な間違いや「かすかな」コードがあれば、あなたのフィードバックをお聞きしたいと思います。
前
を私のデータベースからフィールドを返します。ありがとうございました! –