javascript - 为什么我的获取顺序会改变程序的工作方式?
问题描述
在进行快速编码分配时,我遇到了一个奇怪的错误。
这是我的代码。让我们称之为“A”
//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
{
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const query = "SELECT * FROM animals";
connection.query(query, (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
而这个'B'
//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
{
console.log("Fetching user with id: " + req.params.id);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const animalId = req.params.id;
const query = "SELECT * FROM animals WHERE id = ?";
connection.query(query, [animalId], (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
出于某种原因,如果我将 A 放在 B 之前,它会起作用,并且我会从查询中获得成功的结果。但是,如果我将 B 放在 A 之前,B 将成功返回,但 A 将返回 '[]'。有谁知道为什么?
谢谢你的帮助!
解决方案
您是否尝试在每次请求后终止连接,或考虑使用连接池?我不熟悉nodeJS与MySQL的集成,但是在SQLServer中,异步进行数据库请求时最好使用ConnectionPool。
推荐阅读
- mongodb - 如何在连接 mongodb 时修复“[nodemon] 应用程序崩溃 - 在启动前等待文件更改”
- java - 引用 Maven jar 文件的 Jar 文件无法始终如一地工作
- javascript - 为什么单击按钮时没有出现我的黑色叠加层?
- azure-devops - 如何在 Azure 构建管道中使用 Powershell 修改流程变量
- python - np.random.choice 在直方图中有间隙
- dataframe - 如何将 pyspark 数据帧 1x9 转换为 3x3
- lua - 未找到模块“cudnn”
- python - 尝试使用 python -m pip install datatable 在 python 3.7.4 中安装数据表时收到错误消息
- javascript - 如何将所有包含连字符/破折号(?)的类应用于任何 DOM 元素并将它们保存到 JavaScript 中的数组中?
- c# - 如何在 C# 中获取磁盘利用率信息