简体   繁体   中英

Can I use 2 different functions on the same route? Node.js

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.

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
}

您的第一个函数接收3个输入(request, response, next) ,在此函数的结尾,调用next()

您只需将uploadPicture放在uploadPicture内, addCollection根据需要运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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