如何使用express.js返回mySql查询的结果?

发布于 2025-01-10 15:05:47 字数 1574 浏览 0 评论 0原文

我试图将简单 SELECT 命令的结果获取到 index.js 文件,我希望将所有记录分隔在一个数组中。如果我在database.js 中打印结果,JSON.parse 就可以正常工作。但如果我想返回它们并将它们放入我需要它们的index.js中,那么当我打印它时,我总是会得到未定义的结果。

index.js 代码

const express = require('express');
const app = express();
const database = require('./database');

app.use(express.json());

app.use(express.urlencoded());

app.use(express.static('public'));

app.get('/form', (req,res) =>{
    res.sendFile(__dirname + '/public/index.html' );
    console.log(req.url);
    console.log(req.path);
})


app.listen(4000, () =>{
    console.log("Server listening on port 4000");
    database.connection;
    database.connected();
    //console.log(database.select());
    let results = [];
    //results.push(database.select('username, password'));
    let allPlayer = database.select('username');
    console.log(allPlayer);
});

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){
    let allPlayer = [];
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
    
    if(err) throw err;
        return Object.values(JSON.parse(JSON.stringify(result)));
    })
}
module.exports = {connection, connected, select};

I am trying to get the results of my simple SELECT command to the index.js file, where I would like to have all records separated in a array. If I print the results in the database.js the JSON.parse just work fine. But if I want to return them and get them into the index.js where I need them, I always get undefined when I print it.

index.js CODE

const express = require('express');
const app = express();
const database = require('./database');

app.use(express.json());

app.use(express.urlencoded());

app.use(express.static('public'));

app.get('/form', (req,res) =>{
    res.sendFile(__dirname + '/public/index.html' );
    console.log(req.url);
    console.log(req.path);
})


app.listen(4000, () =>{
    console.log("Server listening on port 4000");
    database.connection;
    database.connected();
    //console.log(database.select());
    let results = [];
    //results.push(database.select('username, password'));
    let allPlayer = database.select('username');
    console.log(allPlayer);
});

database.js CODE

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){
    let allPlayer = [];
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
    
    if(err) throw err;
        return Object.values(JSON.parse(JSON.stringify(result)));
    })
}
module.exports = {connection, connected, select};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万人眼中万个我 2025-01-17 15:05:48

了解 JavaScript 与其他语言的主要区别之一是它 异步,简单来说,意味着代码在完成执行之前不会“等待”代码。因此,当您尝试查询数据库时(这需要一些时间),之后的代码会变得不耐烦,并且无论查询如何执行都会执行。为了解决这个问题,mysql包利用了回调,它允许您将一个函数传递给它,以便在查询完成并获取查询结果后执行。
因为该库对回调进行操作,所以它不会返回任何内容;在其他地方使用它似乎很成问题,不是吗?

为了解决这个问题,我们可以自己制作回调。或者更好的是,使用称为 Promise 的新 JavaScript 功能,您基本上可以从函数中“返回”任何内容,即使您处于回调中也是如此。

让我们用查询来实现它:

function select(attribute) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
      if(err) return reject(err);
      resolve(Object.values(JSON.parse(JSON.stringify(result))));
    });
  });
}

为了从 Promise“返回”,我们将一个值传递给 resolve 函数。要引发错误,我们以错误作为参数调用 reject 函数。

我们的新功能相当容易使用。

select("abcd").then(result => {
  console.log("Result received:", result);
}).catch(err => {
  console.error("Oops...", err);
});

您可能会查看这段代码,然后说:“等一下,我们仍在使用回调。这并不能解决我的问题!”
隆重推出 async/await,该功能可让您轻松使用该功能。我们可以这样调用该函数:

// all 'await's must be wrapped in an 'async' function
async function query() {
  const result = await select("abcd"); // woah, this new await keyword makes life so much easier!
  console.log("Result received:", result);
}
query(); // yay!!

要实现错误捕获,您可以将内容包装在 try {...} catch {...} 块中。

Understand that one of the main things that make JavaScript different from other languages is that it's asynchronous, in simple terms meaning code doesn't "wait" for the code before it to finish executing. Because of this, when you're trying to query a database, which takes some time, the code after it gets impatient and executes regardless of how to the query is doing. To solve this problem, the mysql package utilizes callbacks, which allows you to pass a function to it to execute once the query is finished with the queries result.
Because the library operates on callbacks, it doesn't return anything; that seems quite problematic for using it somewhere else, doesn't it?

To solve this problem, we can make our own callback. Or better yet, use the newer JavaScript feature called promises, where you can basically "return" anything from a function, even when you're in a callback.

Let's implement it with the query:

function select(attribute) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
      if(err) return reject(err);
      resolve(Object.values(JSON.parse(JSON.stringify(result))));
    });
  });
}

To "return" from a promise, we pass a value to the resolve function. To throw an error, we call the reject function with the error as the argument.

Our new function is rather easy to use.

select("abcd").then(result => {
  console.log("Result received:", result);
}).catch(err => {
  console.error("Oops...", err);
});

You might look at this code and go, "Wait a minute, we're still using callbacks. This doesn't solve my problem!"
Introducing async/await, a feature to let you work just with that. We can call the function instead like this:

// all 'await's must be wrapped in an 'async' function
async function query() {
  const result = await select("abcd"); // woah, this new await keyword makes life so much easier!
  console.log("Result received:", result);
}
query(); // yay!!

To implement error catching, you can wrap you stuff inside a try {...} catch {...} block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文