简体   繁体   English

在module.exports中使用需要模块变量的函数

[英]Use function within module.exports that requires module variable

So I am trying to avoid requiring more than once and so I am designing all of my modules to take arguments from the main app.js file. 因此,我试图避免要求不止一次,因此,我设计了所有模块以从主app.js文件中获取参数。 I have a module for users to login that looks like this: 我有一个供用户登录的模块,如下所示:

module.exports = (express, router, jwt, user, config) => {
  function jwtSignUser (user) {
    const ONE_WEEK = 60 * 60 * 24 * 7
    return jwt.sign(user, config.authentication,jwtSecret, {
      expiresIn: ONE_WEEK
    })
  }
  router.post('/login', function(req, res, next) {
    const result = user.findOne(
      {
        email: req.body.email   
      },
      function (err, user) {
        if (err) {
          res.status(400).send(err)
        }
        console.log(user)
        res.send({
          user: user,
          token: jwtSignUser(user)
        })
      }
    )
  })
  return router
}

But when I try to run it I get an error TypeError: jwtSignUser is not a function 但是,当我尝试运行它时,出现错误TypeError: jwtSignUser is not a function

How can I use this function but still have the module take in the arguments necessary for the function (like jwt)? 如何使用此功能,但模块仍要接受该功能所需的参数(如jwt)? Is there a better way I can structure this? 有没有更好的方法可以构造此结构? I am a newbie to Javascript 我是Java语言的新手

I don't know if this is the "best" way to do this. 我不知道这是否是“最佳”方法。 But I did some re-factoring and got it to work by doing the following: 但是我做了一些重构,并通过执行以下操作使其起作用:

var jwtSignUser = (jwt, config, user) => {
  const ONE_WEEK = 60 * 60 * 24 * 7
  return jwt.sign(user, config.authentication.jwtSecret, {
    expiresIn: ONE_WEEK
  })
}

var main = (express, router, jwt, user, config) => {
  router.post('/login', function(req, res, next) {
    const result = user.findOne(
      {
        email: req.body.email   
      },
      function (err, user) {
        if (err) {
          res.status(400).send(err)
        }
        console.log(user)
        res.send({
          user: user,
          token: jwtSignUser(jwt, config, user.toObject())
        })
      }
    )
  })
  return router
}

module.exports = main

Update 更新资料

This is not the true reason for why this code now works. 这不是此代码现在起作用的真正原因。 There is a part where I have config.authentication,jwtSecret which should be config.authentication.jwtSecret . 我有一个部分config.authentication,jwtSecret应该是config.authentication.jwtSecret It now seems to work regardless of where I stick the jstSignUser function 现在无论我将jstSignUser函数放在哪里都可以正常工作

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

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