Express.js multiple methods

前端 未结 4 2077
别跟我提以往
别跟我提以往 2021-01-12 02:30

So in Express you can do:

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

and

app.a         


        
相关标签:
4条回答
  • 2021-01-12 03:08

    another version:

    ['get','head'].forEach(function(method){
      app[method]('/logo/:version/:name', function (req, res, next) {
        // Do something
      });
    });
    
    0 讨论(0)
  • 2021-01-12 03:18

    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);
    
    0 讨论(0)
  • 2021-01-12 03:23

    You can use .route() method.

    function logo(req, res, next) {
        // Do something
    }
    
    app.route('/logo/:version/:name').get(logo).head(logo);
    
    0 讨论(0)
  • 2021-01-12 03:33

    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();
    });
    
    0 讨论(0)
提交回复
热议问题