0

In the express documentation, there is the following example:

app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

and it explains that the function is executed for any type of HTTP request on the /user/:idpath. This confuses me as it looks like app.use does the same work as app.all(). Are they the same?

In describing app.use, the documentation always uses the terms mount and path. Whereas for app.get, the term used is always route. What do all these mean?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • 3
    possible duplicate http://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js – Asif Saeed Jan 28 '17 at 08:54
  • 1
    Possible duplicate of [Difference between app.use and app.get in express.js](http://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js) – cartant Jan 28 '17 at 09:00

3 Answers3

0

app.use is typically used for middleware (like cors or a logger). Use app.get when you need to make a get request on your resource.

Edward Smith
  • 542
  • 1
  • 5
  • 12
0

The documentation says app.use(....) is executed for ANY type of HTTP request on the /user/:id path whereas the app.get(...) (as an example of app.METHOD ) handles (specifically) GET request made to the given path, same applies to app.post() which ONLY handles HTTP post request.

0

I understand the router is just another function. Typically router expects mount path not being visible; otherwise in your router you need to repeat the mount path.

router with app.use("/users", router)
router.get('/', function(req, res) {});
router.get('/test', function(req, res) {});

router with app.get("/users", router)
router.get('/users/', function(req, res) {});
router.get('/users/test', function(req, res) {});

in order to use the router with .get the mounting path is repeated making it much less useful.

   app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo

Notice the difference between use and get? These mean different things in Express.js:

  • use means “Run this on ALL requests”
  • get means “Run this on a GET request, for the given URL”
Adiii
  • 54,482
  • 7
  • 145
  • 148