ExpressJS在路由中调用路由

1 controller node.js express

我正在使用NodeJS构建一个基本网站,作为个人学习过程的一部分.

所以这是我的问题,我已经创建了一个带有CRUD功能的基本用户API,这是我的创建用户方法.

app.route('/api/users')
    .post(function(request, response) {

        var hash = bcryptjs.hashSync(request.body.password, bcryptjs.genSaltSync(10));

        var user = new User({
            firstname: request.body.firstname,
            lastname: request.body.lastname,
            email: request.body.email,
            password: hash
        });

        user.save(function(error) {
            if(error) {
                response.send(error);
            } else {
                response.send('User Successfully Created!');
            }
        })

    });
Run Code Online (Sandbox Code Playgroud)

好吧,所以基本上这个我想创建一个控制器来处理登录和注册过程,那么我将如何使用其他路由,即/ login来调用这些路由?

所以,在理论上,像这样:

app.post('/login, function(request, response) {

    // call the api method, and pass this request to use in the POST api method
    app.call('/api/users/', request.body);

});
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助!

Vse*_*nin 7

用一些代码示例解释我的想法.

您可以定义此功能:

function saveUser(request, response, callback) {    

   var hash = bcryptjs.hashSync(request.body.password, bcryptjs.genSaltSync(10));

    var user = new User({
        firstname: request.body.firstname,
        lastname: request.body.lastname,
        email: request.body.email,
        password: hash
    });

    user.save(function(error) {
        if(error) {
            callback(err);
        } else {
            callback(null);
        }
    })
})
Run Code Online (Sandbox Code Playgroud)

然后你可以从两个路由处理程序中调用它:

app.route('/api/users').function(function(req, res) {
   saveUser(req, res, function() {
      return res.json({success: true});
   });
})

app.post('/login').function(function(req, res) {
   saveUser(req, res, function() {
      return res.render("some_view");
   });
})
Run Code Online (Sandbox Code Playgroud)

你也可以用承诺来定义的处理程序,使用then和catch如果你喜欢.