繁体   English   中英

如何在函数内的node.js中返回导入的模块?

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

我正在创建一个node.js单页应用程序。 如果用户已通过身份验证,我想在首页中显示特定视图。 为此,我创建了一个函数来检查用户是否为auth。 工作正常。

但是,当我想返回特定的视图时,会遇到一些问题。

我尝试了几种不同的方法,但是我无法返回任何视图。

意见

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

这是我的第一次尝试:

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

然后,我尝试仅使用module.exports

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

最后,我尝试了这个:

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

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

注意:

如果使用以下示例,则需要具有特定视图的每个模块都可以正常工作:

module.exports = notAuth

如何在函数中返回特定的导入模块?

也许您需要将上下文实际传递到目标路线

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM