问题
I have checked many answers in other pages and forums, but I still don't get it. What did I do wrong? Help me
*edited. I have added requiring routes and app.use. It looks like function isLOggedIn is not exporting but I don't know how to do that. I did like this in another app, it worked there.
auth-routes.js
const express = require("express"),
router = express.Router(),
passport = require("passport")
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect("/auth/login")
}
module.exports = router
user-routes.js
const express = require("express"),
router = express.Router(),
authRoutes = require("./auth-routes")
router.get("/profile", authRoutes.isLoggedIn, (req, res) => {
res.render("user/profile", {user: req.user})
})
module.exports = router
requring routes
const titleRoutes = require("./routes/title-routes")
const authRoutes = require("./routes/auth-routes")
const userRoutes = require("./routes/user-routes")
app.use
app.use(titleRoutes)
app.use("/auth", authRoutes)
app.use("/user", userRoutes)
回答1:
In auth-routes.js
you don't export isLoggedIn
. So in user-routes.js
, authRoutes.isLoggedIn
is undefined
.
You can change:
module.exports = router
into:
exports.isLoggedIn = isLoggedIn
or using module.exports
into:
module.exports = { isLoggedIn: isLoggedIn }
A useful link to understand export in nodejs https://www.sitepoint.com/understanding-module-exports-exports-node-js/
来源:https://stackoverflow.com/questions/59506203/route-get-requires-a-callback-function-but-got-a-object-undefined-what-did