user5280866
user5280866

Reputation:

ExpressJS Calling Routes within Routes

I'm using NodeJS to build a basic website as part of a personal learning process.

So here's my issue, I've created a basic User API with CRUD functionality, here's my create user method.

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!');
            }
        })

    });

Okay, so basically with this I want to create a controller to handle the login and register process, so how would I essentially use other routes i.e. /login to call these routes?

So, in theory, like this:

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);

});

Thank you for any help!

Upvotes: 1

Views: 3406

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

Explaining my idea with some code example.

You can have this function defined:

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);
        }
    })
})

Then you can call it from both route handlers:

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");
   });
})

You can also use Promises to define the handler, to use then and catch if you like.

Upvotes: 7

Related Questions