7

I am working with nodejs/express. I want to do the same thing for a route, for GET and POST http requests.

I am doing this:

  app.get('/', function(req, res) {
    // Some code
  });

  app.post('/', function(req, res) {
     // Same code
  });

Is there a way to refactor get and post in the same callback ?

Thanks

3
  • 1
    why not just use one or the other exclusively? having POST do the same thing as GET is not the proper usage of the two HTTP methods.
    – Seth
    May 13, 2016 at 15:56
  • It is for the login page: When you first come on the login page, you come with a GET request. When you type a bad login, you stay on the same page, but this is a POST request
    – testpresta
    May 13, 2016 at 15:59
  • Just redirect the user on a bad request...
    – Seth
    May 13, 2016 at 17:00

3 Answers 3

19

Or you can use all, if your site doesn't use any other methods in particular:

app.all('/', handler)
13

This seems like a very odd requirement. If the behavior is exactly the same just specify one function to handle both:

 function myHandler(req, res) {
   // Some code
 }

 app.get('/', myHandler);
 app.post('/', myHandler);
3
  • Your a better typist than me ! May 13, 2016 at 15:53
  • 1
    Inside the myHandler you can test what method was used by if(req.method === 'GET') ...
    – m.e.conroy
    Apr 26, 2019 at 16:38
  • 1
    You can use router.route('/').get().post() in order to avoid dupe path.
    – Ryan
    Feb 10, 2020 at 3:46
4

A bit old question but still facing today.

If you want to expose the api for all method with the same handler:

function sameHandler(req, res) {
  // do something here
}
app.all('/', sameHandler);

If just wanna use the same route but with different handlers:

function getHandler(req, res) {
  // do something here
}
function postHandler(req, res) {
  // do something here
}
function deleteHandler(req, res) {
  // do something here
}
app.route('/').get(getHandler).post(postHandler).delete(deleteHandler);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.