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)
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268

1 Answers1

4

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/

C_Ogoo
  • 5,365
  • 3
  • 17
  • 34
Taymer
  • 164
  • 5
  • Can you add more info ? How the app is definded, how the routes are used and the error log – Taymer Dec 28 '19 at 08:47
  • /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); ^ – Booi Mangang Dec 28 '19 at 18:03
  • I have edited my question. Help me, please. I am stuck. – Booi Mangang Dec 28 '19 at 18:23
  • I can't help you if I don't see your full code (or at least the important parts) and the error stacktrace – Taymer Dec 28 '19 at 21:35
  • It's ok now. I move the method to another folder and export from there. It works now. Thanks for trying. – Booi Mangang Dec 29 '19 at 10:35