[英]How to import data from a database and store it in a variable in a node.js app for later use
I want to try and get data from a database(in my case, questions) and save them in an array to be used in the rest of my javascript code.我想尝试从数据库中获取数据(在我的情况下是问题)并将它们保存在一个数组中,以便在我的 javascript 代码的 rest 中使用。
I have been doing some reading and tests with mysql in node.js, and how it is asynchronous.我一直在对 node.js 中的 mysql 进行一些阅读和测试,以及它是如何异步的。 I've been able to get the data after querying, but I can't store the data elsewhere in my code, and I want to know what to do to get the database data, store it, and use it for other areas in my js code.
查询后我已经能够获取数据,但是我无法将数据存储在代码中的其他位置,我想知道如何获取数据库数据,存储它,并将其用于我的其他区域js代码。
Here is one of my tests这是我的测试之一
This is part of the server javascript这是服务器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);
});
Here is part of the client javascript这是客户端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);
}
})
This code returns the error: "Cannot read property 'push' of undefined"此代码返回错误:“无法读取未定义的属性 'push'”
You need to initialize your array before you can push
to it您需要先初始化数组,然后才能
push
送到它
let questions = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.