【问题标题】:MVC Express + MySQL return TypeError: Cannot read property 'showAll' of undefinedMVC Express + MySQL 返回 TypeError:无法读取未定义的属性“showAll”
【发布时间】:2021-07-06 18:45:00
【问题描述】:

我遇到了一个正在运行的网站的问题。我有一个 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: Cannot read property 'showAll' of undefined

【问题讨论】:

    标签: mysql node.js model-view-controller


    【解决方案1】:

    您的控制器实际上导出了您的 showAll() 函数的调用 - 返回 undefined

    因此,您的路由文件中的 articleController 变量等于 undefined,当您调用 articleController.showAll() 时,您尝试访问 undefined 值上的 showAll 属性 - 这不是有效的操作并抛出你看到的错误。

    编辑:如果要导出showAll() 函数,只需导出对它的引用而不是实际调用它:

    module.exports = showAll
    

    然后在导入你的模块的时候,你会得到这个函数的直接引用

    const showAll = require("./controller/articleController");
    

    【讨论】:

    • 您好!谢谢!那么,我应该导出什么?看不懂
    • 现在它告诉我 Route.get() 需要一个回调函数但得到了一个 [object Undefined]
    • 您很可能调用了 router.get("/", showAll()) 而不是 router.get("/", showAll)。同样,您只需向您的路由器传递对您的函数的引用,它会在相关时调用它 - 即当请求路由时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2013-01-19
    • 2020-05-20
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多