1

I have 2 different methods that I want to be called when a specific form is filled. I know that I can't have a form with 2 actions so I am just wondering can I call 2 different methods on the same route in Node.js?

I need something like this

router.post('/webmark/addcollection', webmarks.addCollection);
router.post('/webmark/addcollection', webmarks.uploadPicture);

so basically when the button in the form is pressed, the action would redirect to the specific route and the 2 methods would be called.

4
  • 2
    Can't you just put the uploadPicture inside the addCollection? Commented Apr 22, 2018 at 14:06
  • Think calling next() function in first route solve your problem Commented Apr 22, 2018 at 14:22
  • @Colin Thanks man, I looked over the code and that actually fixed my problem. Since no answers worked. Commented Apr 22, 2018 at 14:36
  • Cool, I'll add it as an answer. Commented Apr 22, 2018 at 14:38

3 Answers 3

3

No, if do it that way, then you will be overwriting the first.

A better approach to that is like below:

router.post('/webmark/addcollection', webmarks.addCollection, webmarks.uploadPicture);

And make sure you make the call to next middleware function here uploadPicture from addCollection handler by adding next() in addCollection middleware on the successful operation.

exports.addCollection = function(req, res, next){
  // You logic goes here
  // On success operation call next middleware

  next();
}

exports.uploadPicture = function(req, res){
  // You logic for uploadPicture
}
Sign up to request clarification or add additional context in comments.

2 Comments

This didn't work. It only called the addCollection method for some reason.
did you call next middleware in after successful operation in addCollection?
0

You can just put the uploadPicture inside the addCollection and it will work as you want.

Comments

0

Your first function receives 3 input (request, response, next), at the end of this function, call next().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.