[英]Express TypeError: Cannot read property 'get' of undefined
I'm refactoring my routes into a separate folder: 我将路线重构到一个单独的文件夹中:
server.js: server.js:
var express = require("express"), parse = require("body-parser"), db = require("mysql"), mailer = require("nodemailer"), redirectToHTTPS = require("express-http-to-https").redirectToHTTPS, app = express(); var indexRoutes = require("./routes/index"), deviceRoutes = require("./routes/devices"), locationRoutes = require("./routes/locations"), organizationRoutes = require("./routes/organizations"); app.use(parse.urlencoded({extended: true})); app.set("view engine", "ejs"); app.use(express.static(__dirname + "/public/")); app.use(redirectToHTTPS([/localhost:(\\d{4})/], [/\\/insecure/], 301)); //---------------------------------ROUTING-------------------------------------- app.use("/", indexRoutes); app.use("/devices", deviceRoutes); app.use("/locations", locationRoutes); app.use("/organizations", organizationRoutes); //-------------------------------SERVER INIT------------------------------------ app.listen(process.env.PORT, process.env.IP, function(){ console.log("Server initiated (port " + process.env.PORT + ")..."); });
index.js (where my index routes are): index.js(我的索引路由所在的位置):
var express = require("express"); var router = express.Router(); //------------------------------------------------------------------------------ router.get("/", function(req, res){ res.render("home"); }); //------------------------------------------------------------------------------ module.exports = router;
But, 但,
I am getting a TypeError: 我收到一个TypeError:
Cannot read property 'get' of undefined
无法读取未定义的属性“ get”
I have no idea what is going on, as a previous project I worked on had the exact same handling and had no issues whatsoever. 我不知道发生了什么,因为我从事的上一个项目具有完全相同的处理方式,没有任何问题。 I am using express 3.21.2.
我正在使用Express 3.21.2。
Important to note that the error is in all 4 of the route files , I just happen to get the error in the index file since it is the first one. 需要特别注意的是该错误是所有四个路由文件中的错误,因为它是第一个错误,所以我恰好在索引文件中得到了错误。
I believe this is because you're using version 3.x of Express which doesn't include express.Router()
(so all subsequent usage of it in your routes files is invalid). 我相信这是因为您正在使用Express 3.x版, 其中不包含
express.Router()
(因此,其在路由文件中的所有后续使用均无效)。 I'd encourage you to upgrade to the current version, 4.x, which is actively maintained. 我鼓励您升级到当前版本4.x,该版本已得到积极维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.