繁体   English   中英

谁能帮我 node.js,用搜索框查询数据库

[英]Can anyone help me with node.js, database querying with a search box

所以我正在为卡路里计数器应用程序创建一个 web 应用程序,我目前停留的页面是搜索食物页面,因此用户在搜索栏中输入食物,如果它在我创建的数据库中,它将显示食物和它的所有营养,

现在这一切正常,但是如果用户输入的食物不在数据库中或拼写错误,它应该会在屏幕上显示一条消息,说明这一点。

这是我的 main.js 文件

app.get("/search-result", function (req, res) {
    //searching in the database
       let word = [`%${req.query.name}%`];
       let sqlquery = `SELECT * FROM food WHERE name LIKE '%${req.query.name}%'`;
       db.query(sqlquery, (err, result) => {
           if (err)  {
                return console.error('There is no food with that name' + req.query.name);
            }else{
                res.render('ListFood.html', {availableFood: result});
               }
           });
       });

这是我的 index.js 文件

const express = require ("express");
const bodyParser = require ("body-parser");
const app = express();
const mysql = require("mysql");
const port = 8089;
app.use(bodyParser.urlencoded({ extended: true }));
const db = mysql.createConnection ({
 host: "localhost",
 user: "root",
 password: "root",
 database: "foodList" });
// connect to database
db.connect((err) => {
 if (err) {
 throw err;
 }
 console.log("Connected to database");
});
global.db = db;
require("./routes/main")(app);
app.set("views",__dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

这是我搜索的food.html查看文件

<!doctype html>
<html>
 <head>
 <title>Search</title>
 </head>
 <body>
 <h1> Food Search page </h1>
 <p>In the box below please type in the name of the food you would like to search for in our database. If the food is in the database it will show you the nutritonal values, if it is not in our database and you would like to add it in, please visit the Add Food page.</p>
 <form action="/topic7/mid-term/search-result/" method="GET">
 <input id="search-box" type="text" name="name" value="Food Name">
 <input type="submit" value="Submit" >
 </form>
 <br>
     <a href="/topic7/mid-term/"><strong>HOME</strong></a>
 <br>
 </body>
</html>

最后这是我的食物清单。html,这是食物正确时显示的页面,但即使食物不在数据库中,也似乎无法阅读标题和 header

<!doctype html>
<html>
 <head>
 <title>List webpage!</title>
 </head>
 <body>
 <h1> Food List </h1>
 <h3>You can see names and nutritional values of different food here:</h3>
 <ul>
 <% availableFood.forEach(function(food){ %>
 <li><%= food.name %>, Typical Value: <%= food.typicalvalues %>, Unit of typical value: <%= food.Unitofthetypicalvalue %>, calories: <%= food.calories %>, carbs: <%= food.carbs %>, fat: <%= food.fat %>, protein: <%= food.protein %>, salt: <%= food.salt %>, sugar: <%= food.sugar %></li>
 <% }) %>
 </ul>
 </body>
 </html>

我已经看了好几个小时了,但似乎无法弄清楚为什么。 我对此很陌生,因此非常感谢任何帮助。

据我所知,查询 function 仅在查询数据库时出现实际错误而不是在未找到任何元素时返回错误。 即使没有找到任何元素,function 也会给你的回调一个结果 object。 虽然我不确定 object 的结构,但是通过一些控制台日志记录,您应该能够找到从查询返回的元素数量的位置。

您必须查看零长度结果以显示正确的未找到错误消息。

(err, result) => {
    if (err)  {
        console.error('Database error in query data');
        res.render('500.html')
        return
    }
    if (result.length === 0) {
        //show not found error
        console.error('There is no food with that name' + req.query.name);
        res.render('ListFoodEmpty.html')
    }else{
        res.render('ListFood.html', {availableFood: result});
    }
});

要遵循的一些选项

在我的示例中,我在渲染 function 中使用了'ListFoodEmpty.html'作为参数。 如果你选择这种方式,你必须实现一个默认的 html 模板来处理未找到的结果。

或者,您可以重用您的ListFood.html模板并在运行forEach之前检查零长度数组,并为未找到的结果添加适当的错误消息。 如果您选择这种方式,您可以保留您的路线/search-result并更改ListFood.html模板。

我也想指出,如果您在对数据库运行查询之前没有验证您的字符串,那么您对sql injection atacks 持开放态度。 您必须使用数据库库提供的准备好的语句,并在运行前清理和验证输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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