Middleware in Express
- Look at https://github.com/kurmasz-SampleCode/CIS371-SampleCode/tree/master/ExpressRouting
- First few examples (
books, toys) just demonstrate that the first route to match is run, so choose route orders carefully.
- Any questions about
req and res parameters?
- The
authors routes demonstrate the use of next
- Calling
next() runs the code for the next route that matches. (e.g., /authors/105)
- You can also provide a list of blocks. In this case,
next() invokes the next block in the list.
- If
next() is called on the last handler on the list, then move to the next matching route.
- These blocks can also be defined as separate functions and used with multiple routes.
- See
/dogs and numbersOnly
- See
/colors and both numbersOnly and evensOnly
- This is how we can enforce logins in frameworks like Express
- There is one short-cut:
use.
use applies the block to every route.
- Things like
app.use(bodyParser.urlencoded({ extended: true })) and app.use(session({...})
are just hooks that cause “setup” code to run before a routes “primary” block is run.
- e.g., parse the request for post parameters, check the session cookie, etc.