ReferenceError:找不到变量:需要。我该如何修复这个错误?
我想从我的database.js 文件中导出一些函数,并将它们添加到同一文件夹中的另一个文件login.js 中。我还尝试在全局和函数中声明 require,这两种方法都不起作用。我正在使用node.js/express.js。
DATABASE.JS
let mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
database: 'minigames',
user: 'root',
password: 'root'
});
function connected(){
connection.connect((err) => {
if(err) throw err;
console.log("Connected...");
})
}
function select(attribute){
return new Promise((resolve, reject) => {
let sql = `SELECT ${attribute} FROM player`;
connection.query(sql, (err, result, field) => {
if(err) reject(err);
resolve(Object.values(JSON.parse(JSON.stringify(result))));
})
})
}
async function query(attribute) {
return await select(attribute);
}
module.exports = {connection, connected, select, query};
LOGIN.JS
let userList = [];
function checkLogin(){
const database = require('./database');
let userListPromise = database.query('username, password');
userListPromise
.then()
.then((values) =>{
let i = 0;
while(values[i] != null){
userList.push(values[i]);
i++;
}
console.log("list filled");
console.log(userList);
})
}
checkLogin();
I want to export some functions from my database.js file and require them into the other file login.js, which is in the same folder. I tried also to declare the require globally and in a function, both ways did not work. I am using node.js/express.js.
DATABASE.JS
let mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
database: 'minigames',
user: 'root',
password: 'root'
});
function connected(){
connection.connect((err) => {
if(err) throw err;
console.log("Connected...");
})
}
function select(attribute){
return new Promise((resolve, reject) => {
let sql = `SELECT ${attribute} FROM player`;
connection.query(sql, (err, result, field) => {
if(err) reject(err);
resolve(Object.values(JSON.parse(JSON.stringify(result))));
})
})
}
async function query(attribute) {
return await select(attribute);
}
module.exports = {connection, connected, select, query};
LOGIN.JS
let userList = [];
function checkLogin(){
const database = require('./database');
let userListPromise = database.query('username, password');
userListPromise
.then()
.then((values) =>{
let i = 0;
while(values[i] != null){
userList.push(values[i]);
i++;
}
console.log("list filled");
console.log(userList);
})
}
checkLogin();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论