Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js multiple 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 just have two methods (ie. GET and HEAD)? Such as:

app.get.head('/logo/:version/:name', function (req, res, next) {
    // Do something
}    
like image 921
Justin Cloud Avatar asked Nov 19 '14 19:11

Justin Cloud


People also ask

How does Express handle multiple routes?

Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.

Can a request have two same routes?

Short answer is no.

What does Express () method do?

Express OverviewAllows to set up middlewares to respond to HTTP Requests. Defines a routing table which is used to perform different actions based on HTTP Method and URL. Allows to dynamically render HTML Pages based on passing arguments to templates.

What is scaffolding in Express JS?

Scaffolding is creating the skeleton structure of application. It allows users to create own public directories, routes, views etc. Once the structure for app is built, user can start building it. Express is the open source web development framework for Node.


2 Answers

You can use .route() method.

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

app.route('/logo/:version/:name').get(logo).head(logo);
like image 74
Rahil Wazir Avatar answered Oct 13 '22 12:10

Rahil Wazir


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 general middleware function and check the req.method:

app.use('/logo/:version/:name', function(req, res, next) {
  if (req.method === 'GET' || req.method === 'HEAD') {
    // Do something
  } else
    next();
});
like image 34
mscdex Avatar answered Oct 13 '22 12:10

mscdex