You've already been using it, now learn what Express middleware is!
[MUSIC] 0:00 We already used some Express Middleware in our project. 0:04 We use the body poster to post incoming form data and 0:08 the cookie poster to read cookie information. 0:12 But that's not all you can do with Middleware. 0:16 In fact, Middleware is so integral to Express, 0:18 just about everything you write in Express is Middleware. 0:21 So what is it? 0:24 Consider when someone asks you a question, you hear the question, think about it for 0:25 a moment, and then answer the question. 0:30 If we relate this to the request response cycle, that middle step, 0:33 the thinking, is analogous to what Middleware does. 0:37 An Express application receives requests and sends responses. 0:42 You can sort of think of Express' request response cycle like a conveyor belt. 0:46 The result comes in at the beginning and the response leaves at the end. 0:51 All along the conveyor belt Middleware acts upon the requests, 0:55 packaging up a response to send back to the end user. 0:59 There can be as many pieces of Middleware as you want to have before sending 1:03 a response. 1:07 The basic structure of Middleware code is very simple. 1:09 It's a function with three parameters, request, response and next. 1:13 Inside the function, Middleware can read and modify the request and 1:19 response objects. 1:22 For example, the cookie parser modified the response object, 1:23 placing the cookie's contents onto it. 1:27 Next is a function that must be called, when the work is done. 1:31 This triggers the Middleware function after the current one to execute. 1:34 To run Middleware in response to requests, pass it into app.use. 1:39 This will run the Middleware function for every request. 1:45 To only run it for 1:48 a specific route, pass the router argument in before the Middleware function. 1:49 You can also limit the Middleware to only use get requests. 1:56 This is done by using get instead of use. 2:01 Hopefully this is looking familiar. 2:04 This is very similar code to what we've been running to handle our routes. 2:07 The only difference is that we haven't been declaring or using next yet, but 2:11 we'll get to that soon. 2:15 In the next video, let's write some Middleware to get a better feel for 2:18 how it works. 2:21
You need to sign up for Treehouse in order to download course files.Sign up