简体   繁体   中英

How to return an imported module in node.js within a function?

I'm a creating a node.js single page app. I want to show a specific view in homepage if user is authenticated. For this purpose, I created a function to check if user is auth. It works fine.

However, when I want to return a specific view, I get some problems with this.

I have tried a few different approaches, but I cannot return any view.

views

const notAuth = require('../view1')
const isAuth = require('../view2')

This was my first attempt:

const home = function (ctx) {
  if (ctx.auth) {
    return isAuth
  } else {
    return notAuth
  }
}
module.exports = home

Then, I tried to use module.exports only:

module.exports = function home (ctx, next) {
  if (ctx.auth) {
    return isAuth
  } else {
    return notAuth
  }
  next()
}

And finally, I tried this:

const authenticated = function (ctx) {
  if (ctx.auth) {
    return isAuth
  } else {
    return notAuth
  }
}

module.exports = function home (ctx, next) {
  return authenticated(ctx)
  next()
}

Note:

Each module I required with a specific view works fine if I use for example:

module.exports = notAuth

How can I return a specific imported module within a function?

Maybe you need to actually pass the context on to the target route

const home = function (ctx, next) {
  if (ctx.auth) {
    return isAuth(ctx, next)
  } else {
    return notAuth(ctx, next)
  }
}

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