Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn what middleware does in Express and what it looks like in code.
Prerequisite Course
For best results, we recommend first taking this prerequisite course...
HTTP Request Methods (GET, POST, etc)
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
[MUSIC]
0:00
Express is described as a routing and
middleware web framework.
0:05
When you work with Express you're
almost always working with middleware.
0:09
So what is middleware?
0:13
Consider when someone asks you a question.
0:15
You hear the question, think about it for
a moment and then answer the question.
0:18
That middle step, the thinking,
is analogous to what middleware does.
0:22
An Express application receives
requests and sends responses.
0:27
If we open up an Express app to see
what happens between a request and
0:33
a response,
it sort of works like a conveyor belt.
0:37
The request comes in at the beginning and
the response leaves at the end.
0:40
All along the conveyor belt,
middleware acts on the requests,
0:45
packaging up a response
to send back to the user.
0:48
There can be as many pieces of
middleware as you want to have
0:51
before sending a response.
0:55
In terms of code, middleware is
a function with three parameters,
0:57
request, response and next.
1:01
Request and response are objects that can
be read and modified in the function.
1:04
Middleware can use
the information in request
1:09
to work out how to handle a response.
1:12
Next is a function that must be
called when the work is done.
1:15
This triggers the next
middleware function to execute.
1:19
Most programmers shorten their request and
response parameter names, to req and res.
1:22
Just as clear a name, but
with a lot less typing.
1:28
To run middleware in response to requests,
pass it to app.use.
1:31
This will run the middleware function for
every request.
1:36
To only run it for
1:39
a specific route, pass a route argument
in before the middleware function.
1:40
You can also limit
the middleware to run only when
1:45
a get request is made by
using get instead of use.
1:48
Get is the most common type
of request made by browsers.
1:52
If you want to look at other request
types, check the teachers notes.
1:56
In the next video, let's write some
middleware to get a feel for how it works.
2:00
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up