Multiple Express.js Methods

So, in Express, you can do:

app.get('/logo/:version/:name', function (req, res, next) {
    // Do something
}    

      

and

app.all('/logo/:version/:name', function (req, res) {
    // Do something
}    

      

Is there a way to only have two methods (i.e. GET and HEAD)? For example:

app.get.head('/logo/:version/:name', function (req, res, next) {
    // Do something
}    

      

+3


source to share


3 answers


Just pull out the anonymous function and give it a name:

function myRouteHandler(req, res, next) {
  // Do something
}

app.get('/logo/:version/:name', myRouteHandler);
app.head('/logo/:version/:name', myRouteHandler);

      



Or use a common middleware function and check req.method

:

app.use('/logo/:version/:name', function(req, res, next) {
  if (req.method === 'GET' || req.method === 'HEAD') {
    // Do something
  } else
    next();
});

      

+6


source


You can use the method .route()

.



function logo(req, res, next) {
    // Do something
}

app.route('/logo/:version/:name').get(logo).head(logo);

      

+7


source


another version:

['get','head'].forEach(function(method){
  app[method]('/logo/:version/:name', function (req, res, next) {
    // Do something
  });
});

      

+1


source







All Articles