Difference between app.all('*') and app.use('/')

后端 未结 7 1922
谎友^
谎友^ 2020-11-29 15:51

Is there a useful difference between app.all(\'*\', ... ) and app.use(\'/\', ...) in Node.JS Express?

7条回答
  •  孤城傲影
    2020-11-29 16:34

    Two differences all above answers don't metion.

    The fisrt one: app.all accepts a regex as its path parameter. app.use does NOT accept a regex.

    The second one: app.all(path,handler) or app[method](path,handler),handler's path must be same to all's path. This is,app[method]'path is complete.

    app.use(path,hanlder),if use's path is complete,the hanlder's path must be '/'.if the use's path is the start of the complete path,the handler path must be the rest of the complete path.

     app.use('/users', users);
    
      //users.js:  the handler will be called when matchs `/user/` path
          router.get('/', function(req, res, next) {
          res.send('respond with a resource');
        });
      // others.js: the handler will be called when matchs `/users/users` path
          router.get('/users', function(req, res, next) {
          res.send('respond with a resource');
        });
    

    app.all('/users', users);
    
    //others.js: the handler wil be called when matchs `/`path
    router.get('/', function(req, res, next) {
         res.send('respond with a resource');
    });
    //users.js: the handler will be called when matchs `/users` path
    router.get('/users', function(req, res, next) {
        res.send('respond with a resource');
     });
    

提交回复
热议问题