我正在尝试在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'来获取搜索输入的值,但实际上在我的情况下返回为undefined。那么,无论如何通过'req.query.key'变量实际接收文本,还有一个更“传统”的方法来制作一个简单的数据库搜索栏吗?
P.S。我对Express和Node.js整体编程仍然很陌生,所以如果您发现任何常见错误或“草率”代码,我很乐意听取您的反馈意见。
答案 0 :(得分:0)
您是否尝试过以下方式获取参数
var key = request.options.key || (request.options.where && request.options.where.key) || request.param('key');
答案 1 :(得分:0)
您可以尝试使用npm body-parser,代替req.params.key,您可以放置req.body.input(其中input是输入元素的名称)。
把这个:
app.use(bodyParser.urlencoded({
extended: true
}));
在模板引擎配置之前(在设置视图之前)