Route.get() requires a callback function but got a [object Undefined]. What did I do wrong?

点点圈 提交于 2021-02-10 07:19:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!