Skip to content

Instantly share code, notes, and snippets.

@Jonalogy
Last active February 2, 2021 17:29
Show Gist options
  • Save Jonalogy/ce6db1d33bf5aa557e0371a584e6b07c to your computer and use it in GitHub Desktop.
Save Jonalogy/ce6db1d33bf5aa557e0371a584e6b07c to your computer and use it in GitHub Desktop.
`app.METHOD` vs `app.use`

app.METHOD vs app.use

app.METHOD(PATH, ROUTE_HANDLER)

  • Apply this for route handlers.
  • METHOD here represents the available node methods HTTP verbs eg. get, post, put, delete ...etc

Syntax:

app.get('/', function(req, res){
  /* Route handler's code block */
})

app.use(PATH, MIDDLEWARE)

  • PATH: Routes starting with PATH triggers the middleware
  • MIDDLEWARE: A function, which is the middleware itself. Notice it shares almost the same function signature as the ROUTE_HANDLER
  • The middleware takes in next method as its last parameter. Running next() signifies the end of the middleware's action, else Express will never know if the middleware has ended, causing an endless loop.

Syntax:

app.use(function(req, res, next){
  /*middleware_1's code block. All routes will trigger this middleware*/
})

app.use('/user' function(req, res, next){
  /*middleware_2's code code. Only routes starting with '/user' will trigger this middleware*/
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment