我工作的网站有问题。我有一个model.js、controller.js和routes.js
模型
const mysql = require("mysql2");
class Article {
Firstname;
LastName;
Age;
id;
static findAll() {
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "ha_test",
});
connection.query("SELECT * FROM users", (err, articles) => {
if (err) return res.send(err);
return articles;
})
}
}
module.exports = Article;
控制器
const Article = require("../models/Article");
function showAll(req, res) {
Article.findAll(function (articles) {
res.render("articles", { articles });
})
};
module.exports = showAll();
路线
const express = require('express');
const router = express.Router();
const articleController = require("./controller/articleController");
router.use(express.json());
router.use(express.urlencoded({ extended: true }));
router.get("/",
articleController.showAll())
module.exports = router;
当我使用nodemon index.js时,它显示给我TypeError:无法读取未定义的属性“show all”
您的控制器实际上导出了showAll()
函数的调用-该函数返回undefined
。
因此,路由文件中的ArticleController
变量等于undefined
,当调用ArticleController.showAll()
时,您尝试访问undefined
值的showAll
属性-这不是一个有效的操作,并抛出您看到的错误。
编辑:如果要导出showAll()
函数,只需导出对它的引用,而不是实际调用它:
module.exports = showAll
那么在导入模块时,您将获得对该函数的直接引用
const showAll = require("./controller/articleController");