如何从数据库导入数据并将其存储在 node.js 应用程序的变量中供以后使用
How to import data from a database and store it in a variable in a node.js app for later use
我想尝试从数据库中获取数据(在我的例子中是问题)并将它们保存在一个数组中,以便在我的 javascript 代码的其余部分中使用。
我一直在 node.js 中使用 mysql 进行一些阅读和测试,以及它是如何异步的。查询后已经能够获取到数据,但是无法在我的代码中的其他地方存储数据,我想知道如何获取数据库数据,存储它,并将其用于我的其他区域js代码.
这是我的一项测试
这是 服务器的一部分 javascript
var questions;
io.on('connection', function(socket){
socket.on('Get Questions', function(){
const db = mysql.createConnection({
host: "localhost",
database: "playerdb",
user: "root",
password: "061298"
});
db.query("SELECT Question FROM quiz_questions", function(err, results){
//if(err) console.log("Oh dear, " + err);
for(var i = 0; i < results.length; i++){
questions.push(results[i]);
}
})
});
io.sockets.emit('Send Questions', questions);
});
这里是客户端的一部分javascript
socket.emit('Get Questions');
socket.on('Send Questions', function(qList){
for(var c = 0; c < questions.length; c++){
const newQuestion = document.createElement('li');
newQuestion.innerHTML = qList[i];
databaseData.appendChild(newQuestion);
}
})
这段代码returns错误:
“无法读取未定义的 属性 'push'”
您需要先初始化数组,然后才能push
它
let questions = [];
我想尝试从数据库中获取数据(在我的例子中是问题)并将它们保存在一个数组中,以便在我的 javascript 代码的其余部分中使用。
我一直在 node.js 中使用 mysql 进行一些阅读和测试,以及它是如何异步的。查询后已经能够获取到数据,但是无法在我的代码中的其他地方存储数据,我想知道如何获取数据库数据,存储它,并将其用于我的其他区域js代码.
这是我的一项测试
这是 服务器的一部分 javascript
var questions;
io.on('connection', function(socket){
socket.on('Get Questions', function(){
const db = mysql.createConnection({
host: "localhost",
database: "playerdb",
user: "root",
password: "061298"
});
db.query("SELECT Question FROM quiz_questions", function(err, results){
//if(err) console.log("Oh dear, " + err);
for(var i = 0; i < results.length; i++){
questions.push(results[i]);
}
})
});
io.sockets.emit('Send Questions', questions);
});
这里是客户端的一部分javascript
socket.emit('Get Questions');
socket.on('Send Questions', function(qList){
for(var c = 0; c < questions.length; c++){
const newQuestion = document.createElement('li');
newQuestion.innerHTML = qList[i];
databaseData.appendChild(newQuestion);
}
})
这段代码returns错误: “无法读取未定义的 属性 'push'”
您需要先初始化数组,然后才能push
它
let questions = [];