Express.js multiple methods

为君一笑 提交于 2020-01-13 09:23:26

问题


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
}    

回答1:


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



回答2:


You can use .route() method.

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

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



回答3:


another version:

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



回答4:


You can also use the array spread operator if your route pattern is the same for multiple methods.

e.g.

const route = [
    '/logo/:version/:name', 
    function handleRequest(req, res) {
        // handle request
    }
];

app.get(...route);
app.post(...route);


来源:https://stackoverflow.com/questions/27025486/express-js-multiple-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!