Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 951
testpresta Avatar asked May 13 '16 15:05

testpresta


2 Answers

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

app.all('/', handler)
like image 118
Mohit Bhardwaj Avatar answered Oct 22 '22 11:10

Mohit Bhardwaj


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);
like image 27
Nick Tomlin Avatar answered Oct 22 '22 10:10

Nick Tomlin