testpresta
testpresta

Reputation: 449

Node JS Express same thing for route GET and POST

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

Upvotes: 7

Views: 10165

Answers (3)

HaiTH
HaiTH

Reputation: 1061

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

Upvotes: 4

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

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

app.all('/', handler)

Upvotes: 19

Nick Tomlin
Nick Tomlin

Reputation: 29211

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

Upvotes: 14

Related Questions