【发布时间】:2019-05-29 00:18:47
【问题描述】:
我正在尝试使用节点 js 将 MySql 数据最终放置在 HTML(实际上是一个 ejs)页面中。
我一直在使用 W3 的节点 js 示例中的以下代码。 https://www.w3schools.com/nodejs/nodejs_mysql_select.asp
我最终想做的是在“结果”上使用 module.exports,并能够访问另一个文件中的数组。我发现这很难完成。
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "testdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
// This is what is logged to the console.
// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' },
RowDataPacket { name: 'Sanitation', address: 'Highway 27' },
RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]
// Above works but it doesn't do what I need it to.
// Below is explained what I need to happen.
var mysql = require('mysql');
var x; // x is undefined
var con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "testdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers",
function (err, result, fields) {
if (err) throw err;
x = result; // If I do a 'console.log(x);' here I get the array above.
// If try to 'module.exports = result;' here, it is
// undefined in the receiving file. });
});
console.log(x); // x is undefined, even though result was stored in x.
我希望'console.log(x);'在代码的底部返回数组,但它是未定义的。这让我认为“con.query”中的任何内容都是本地的。如果是这样,我考虑使用'module. export = result' 在函数中,但这也会在接收文件中返回一个未定义的变量。如果有人知道为什么会发生这种情况,或者如果有解决方案,我将非常感谢您的建议:)
【问题讨论】: