简体   繁体   中英

Express TypeError: Cannot read property 'get' of undefined

I'm refactoring my routes into a separate folder:

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):

 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:

Cannot read property 'get' of undefined

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.

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). I'd encourage you to upgrade to the current version, 4.x, which is actively maintained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM