mysql 在nodejs中从SQL检索数据时出错

w1e3prcc  于 2023-04-05  发布在  Mysql
关注(0)|答案(3)|浏览(124)

我在node js中将数据库连接到项目,连接工作正常,但是当我尝试使用get操作检索数据时,出现了一个我无法解决的错误
sql连接

const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "my password",
database: "test"
});
connection.connect(function (err) {
if (err) throw err
    console.log("connection");
})
module.exports = { connection }

从页面请求

const express = require("express");
const {connection} = require('../../dbConected')
const router = express.Router();

const {
getallstudents
} = require('../controllers/student')
router.get("/", getallstudents)

module.exports = router;

控制器

const {connection} = require('../../dbConected')
module.exports = {
    getallstudents:
    connection.query("SELECT * FROM test.student",function (err,result){
        if (err) throw err;
        console.log(result);
    })
}

错误
get()需要一个回调函数,但得到了一个[object Object]

[nodemon]应用程序崩溃-启动前正在等待文件更改...
谢谢你的帮忙

xkftehaa

xkftehaa1#

这里的主要问题是路由器。get需要一个函数,但在示例中有一个对象代替它。所以'getallstudents'必须是一个函数。

getallstudents:
connection.query("SELECT * FROM test.student",function (err,result){
    if (err) throw err;
    console.log(result);

将此更改为

getallstudents: (function () => {
connection.query("SELECT * FROM test.student",function (err,result){
    if (err) throw err;
    console.log(result);
})(); //not sure about the last two parentheses
lsmepo6l

lsmepo6l2#

您需要传递一个回调,它将成为router.get、RTM https://expressjs.com/en/guide/routing.html的控制器

module.exports = {
    getallstudents: (req, res, next) => {
      // code here
    }
}

然后在这段代码中:

connection.query("SELECT * FROM test.student",function (err,result){
  if (err) throw err;
  console.log(result);
})

而不是执行if (err) throw err; console.log(result);,发送回响应。

connection.query("SELECT * FROM test.student",function (err,result) {
  if (err) {
    return next(err);
  }

  res.json(result);
})

或类似:

module.exports = {
  getallstudents: async (req, res, next) => {
    try {
      res.json(await connection.query("SELECT * FROM test.student"))
    } catch (err) {
      next(err)
    }
  }
}

什么是next(err),rtm:https://expressjs.com/en/guide/error-handling.html#writing-error-handlers

2eafrhcq

2eafrhcq3#

const {connection} = require('../../dbConected')
module.exports = {
    getallstudents:(req, res) => {
       const select = connection.query("SELECT * FROM student")
       let json_select = JSON.stringify(select)
            res.status(200).json({
                json_select
            }).catch(error => {
            res.status(500).json({
                error
            })
        })
    }
}

我在json文件中得到一个错误
“message”:“正在将循环结构转换为JSON\n --〉从具有构造函数'Query'的对象开始\n|property '_timer' -〉object with constructor 'Timer'\n --- property '_object'close the circle”
和GET /getallstudents 500 2.939 ms - 224

相关问题