1 00:00:00,000 --> 00:00:05,115 [MUSIC] 2 00:00:05,115 --> 00:00:09,760 Express is described as a routing and middleware web framework. 3 00:00:09,760 --> 00:00:13,820 When you work with Express you're almost always working with middleware. 4 00:00:13,820 --> 00:00:15,940 So what is middleware? 5 00:00:15,940 --> 00:00:18,234 Consider when someone asks you a question. 6 00:00:18,234 --> 00:00:22,876 You hear the question, think about it for a moment and then answer the question. 7 00:00:22,876 --> 00:00:27,822 That middle step, the thinking, is analogous to what middleware does. 8 00:00:27,822 --> 00:00:33,040 An Express application receives requests and sends responses. 9 00:00:33,040 --> 00:00:37,180 If we open up an Express app to see what happens between a request and 10 00:00:37,180 --> 00:00:40,860 a response, it sort of works like a conveyor belt. 11 00:00:40,860 --> 00:00:45,140 The request comes in at the beginning and the response leaves at the end. 12 00:00:45,140 --> 00:00:48,560 All along the conveyor belt, middleware acts on the requests, 13 00:00:48,560 --> 00:00:51,880 packaging up a response to send back to the user. 14 00:00:51,880 --> 00:00:55,020 There can be as many pieces of middleware as you want to have 15 00:00:55,020 --> 00:00:57,290 before sending a response. 16 00:00:57,290 --> 00:01:01,320 In terms of code, middleware is a function with three parameters, 17 00:01:01,320 --> 00:01:04,420 request, response and next. 18 00:01:04,420 --> 00:01:09,730 Request and response are objects that can be read and modified in the function. 19 00:01:09,730 --> 00:01:12,810 Middleware can use the information in request 20 00:01:12,810 --> 00:01:15,850 to work out how to handle a response. 21 00:01:15,850 --> 00:01:19,390 Next is a function that must be called when the work is done. 22 00:01:19,390 --> 00:01:22,810 This triggers the next middleware function to execute. 23 00:01:22,810 --> 00:01:28,370 Most programmers shorten their request and response parameter names, to req and res. 24 00:01:28,370 --> 00:01:31,330 Just as clear a name, but with a lot less typing. 25 00:01:31,330 --> 00:01:36,130 To run middleware in response to requests, pass it to app.use. 26 00:01:36,130 --> 00:01:39,650 This will run the middleware function for every request. 27 00:01:39,650 --> 00:01:40,390 To only run it for 28 00:01:40,390 --> 00:01:45,310 a specific route, pass a route argument in before the middleware function. 29 00:01:45,310 --> 00:01:48,333 You can also limit the middleware to run only when 30 00:01:48,333 --> 00:01:52,590 a get request is made by using get instead of use. 31 00:01:52,590 --> 00:01:56,590 Get is the most common type of request made by browsers. 32 00:01:56,590 --> 00:02:00,520 If you want to look at other request types, check the teachers notes. 33 00:02:00,520 --> 00:02:04,750 In the next video, let's write some middleware to get a feel for how it works.