admin管理员组

文章数量:1314514

In Node/express I have a POST request that if it contains an id I would like it to call the PUT method instead. No redirect, just how to call the put method from the post method?

router.put('/:id', function(req, res) {
  // code ...
});

router.post('/:id?', function(req, res) {
  if (req.params.id) {
    // call PUT method
  }
});

I don't want to do a redirect, just make it as if it was part of the current request.

In Node/express I have a POST request that if it contains an id I would like it to call the PUT method instead. No redirect, just how to call the put method from the post method?

router.put('/:id', function(req, res) {
  // code ...
});

router.post('/:id?', function(req, res) {
  if (req.params.id) {
    // call PUT method
  }
});

I don't want to do a redirect, just make it as if it was part of the current request.

Share Improve this question asked May 1, 2014 at 20:08 RobRob 11.4k22 gold badges72 silver badges114 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Move the code to a named function and call that instead.

function handlePut(req, res) {
  // code ...
}

router.put('/:id', handlePut);

router.post('/:id?', function(req, res) {
  if (req.params.id) {
    return handlePut(req, res);
  }

  // don't forget to handle me!
});

本文标签: javascriptHow to call PUT router from POST router in Nodejs ExpressStack Overflow