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

1

3

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)
Reclamation answered 27/12, 2019 at 21:30 Comment(0)
L
5

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/

Lowson answered 27/12, 2019 at 21:59 Comment(5)
Can you add more info ? How the app is definded, how the routes are used and the error logLowson
/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) /Error c:\Booi\DevLog\WebDev\wariLeichal\v2\node_modules\express\lib\router\route.js:202 throw new Error(msg); ^Reclamation
I have edited my question. Help me, please. I am stuck.Reclamation
I can't help you if I don't see your full code (or at least the important parts) and the error stacktraceLowson
It's ok now. I move the method to another folder and export from there. It works now. Thanks for trying.Reclamation

© 2022 - 2024 — McMap. All rights reserved.