简体   繁体   English

节点路由模块访问其他模块功能

[英]Node route module access other module functions

I'm trying to use a module to handle my user sign up and login process. 我正在尝试使用一个模块来处理我的用户注册和登录过程。 What I'd like to do is have a module with, for example, a "register" endpoint but rather than putting all the code in the one function, I'd split it into separate parts like validUsername, validPassword etc to check if the given values are acceptable. 我想做的是有一个带有例如“注册”端点的模块,但不是将所有代码放在一个函数中,而是将其拆分为有效用户名,有效密码等单独的部分,以检查是否给定的值是可以接受的。

The trouble I have is that whenever this route is run, I get this error: 我的麻烦是,每当运行此路由时,都会出现此错误:

TypeError: Object #<Object> has no method 'validUsername' TypeError:对象#<Object>没有方法'validUsername'

server.js server.js

var user = require('./routes/user.js')(mongoose, bcrypt);

express.post('/user', user.create);

user.js user.js

module.exports = function(mongoose, bcrypt){
    return {
        validUsername: function(username){
            // Ensure a username is present
            if(username == null){
                return false;
            }

            // Ensure it is at least 2 characters
            if(username.length <= 2){
                return false;
            }

            return true;
        },

        validPassword: function(password){
            // Ensure a password is present
            if(password == null){
                return false;
            }

            // Ensure it is at least 9 characters
            if(password.length < 9){
                return false;
            }

            return true;
        },

        create: function(req, res){
            // Extract the new user data from the post body
            var username = req.body.username || null;
            var password = req.body.password || null;

            // Ensure the details are acceptable
            if(!this.validUsername(username))
            {
                res.send(400,{'field':'username','error':'invalid'});
            }
            else if(!this.validPassword(password))
            {
                res.send(400,{'field':'password','error':'invalid'});
            }
            else
            {
                // ... Create new user etc ...
            }
        }
    };
};

I'm assuming the reason for the error is because when setting up the route, only the 'create' function is passed in and therefore it is unable to "see" the rest of the functions in the same module. 我假设错误的原因是因为在设置路由时,仅传递了“创建”功能,因此无法“看到”同一模块中的其余功能。

So how can I solve this issue and have the create function still access those validation functions when used as a route endpoint? 因此,当用作路由端点时,如何解决此问题并让create函数仍然访问那些验证函数?

The fix is to either use .bind() : 解决方法是使用.bind()

express.post('/user', user.create.bind(user));

or to use a wrapper: 或使用包装器:

express.post('/user', function(req, res) { user.create(req, res); });

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

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