Rob
Rob

Reputation: 11388

How to call PUT router from POST router in Node.js Express?

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.

Upvotes: 1

Views: 8421

Answers (1)

Timothy Strimple
Timothy Strimple

Reputation: 23070

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

Upvotes: 7

Related Questions