0

I am kind of stuck in something. Please help me

The problem i want to solve is -

I am getting some post parameters and i want to route based on those parameters in NodeJs. Now the issue is when i use switch case to route on base of the post params rerouting is not happening.

router.post('/', function (req, res, next) {
    var method = req.body.method;
    switch (method) {
        case 'register_user':
            router.post('/', userController.registerUser);
            break;
        case 'user_login':
            router.post('/', userController);
            break;
}
});
Udit Sarin
  • 59
  • 9
  • Possible duplicate of http://stackoverflow.com/questions/17612695/expressjs-how-to-redirect-a-post-request-with-parameters – crackmigg Mar 12 '16 at 11:10

1 Answers1

2

Your rerouting code inside switch context just appends more middlewares on the path /, not actually do the route as you think.

Revise like this:

router.post('/', function (req, res, next) {
    var method = req.body.method;
    switch (method) {
        case 'register_user':
            // returned since you want route to the function
            return userController.registerUser(req, res, next);
            break;
        case 'user_login':
            return userController(req, res, next);
            break;
    }
});
hankchiutw
  • 1,546
  • 1
  • 12
  • 15
  • Thanks Hank, But i wana reroute only since i want to execute multiple functions one by one like this, router.post('/', a,b,c); where a,b,c are functions.. Doing it your way will make the code messy – Udit Sarin Mar 12 '16 at 10:27
  • Redirect will result in another request and may increase traffic to load balanacer – Udit Sarin Mar 12 '16 at 11:03
  • I don't know if [ES6 generator](http://eladnava.com/write-synchronous-node-js-code-with-es6-generators/) meet your need. You may need to rewrite sub callbacks as generator and use [co](https://www.npmjs.com/package/co) properly. – hankchiutw Mar 12 '16 at 11:55