Hey, guys. 1
In today's lesson, we're going to be talking about Express Middlewares, the man in the middle that 2
you're going to see in a lot of node and express based applications. 3
What exactly is a middleware? 4
Well, it kind of is something that just sits in between the raw requests that come in. 5
So when a request comes into the server and before it gets processed by all of the route handlers, 6
such as our GET, POST, PUT, the functions that we've planned for how to deal with a particular request, there 7
is something in between, namely the Middleware that can work with these requests before they get processed 8
and reach their final destinations. 9
Now, what kind of things can middleware do? 10
Well, one option is to pre-process the requests. 11
So when we know that a request is going to go to multiple handlers, maybe it could be processed by 12
GET, POST or PUT requests, 13
t his intermediate stage where we have our middleware can actually go ahead and change aspects of the 14
request or perform various functions on that request before it goes to its final routing. 15
Also, we can use middleware for Logging the requests. 16
So how long does it take the request to come through? 17
What type of request GET, PUT, POST, etcetera? 18
What is the status of the request being handled? 19
We can also use middleware for Authentication. 20
So before we let the request through to our back-end handlers, we can see if that request is actually 21
came from a client that is authorized to make that request, say, if somebody wants to go and change 22
Facebook's databases to call it Handbook instead of Facebook, we have to make sure that that request 23
is allowed by that user. 24
And then finally, we can also process any errors in the requests. 25
We can identify them and handle those errors before they go through to the handlers as well. 26
So a number of functions can be performed basically before we allow the request through. A really commonly 27
used middleware in Node and Express 28
back-end engineering is something called Body Parser. 29
Body Parser is, as it says, a body parsing middleware. 30
What does that mean? 31
Well, it can look at the request bodies before your handlers actually access them. 32
This basically gives our request a new property called the body property. 33
And very commonly this is used to handle form data. 34
When you create a HTML form, such as when you have a login form and you want the user to put in their username 35
and password, when you press that login button in order to get access to the data that was inputted 36
in there, you might use something like body-parser to parse the body of that POST request. 37
Here's a real life example using code. 38
This is what a HTML form element looks like. 39
It starts with a form tag, closes with a form tag, and the properties that you usually see are "action", 40
which in most cases will refer to the route that you want your server to handle this request. 41
And also you'll have a "method" which usually will describe how you want this data to be processed in 42
your back-end. 43
Is this a form for updating information on your server, or posting information, or deleting information? 44
It could be a number of things, 45
basically. The other parts of the form that you normally see is the "label" and "input" elements. 46
The label is simply the place where we label the next input because an input is usually just a box. 47
It doesn't really tell the user what you expect to go in there. 48
So normally it's a pair where you have a label element followed by an input element. 49
Now the input element usually has two properties that you'll see, "type", 50
so what kind of input is this? 51
And you can have things such as radio buttons, you can have things such as checkbox input, you can 52
have a dropdown list inputs, 53
but the most common one and the simplest is just a text field. 54
And then we have something called "name", which is going to label the data that goes into this input. 55
So if I put in something like my email, blah blah blah@blah blah blah, then that piece of data 56
will have a key 57
associated. 58
So a key / value pair. 59
And the key will be whatever it is you assign the name property to be. 60
We can also add the "required" attribute, which means that this input cannot be submitted until there 61
is a piece of data that's added into it. 62
And finally, we have a type of input that is a "submit" type, which actually is a button, and you can 63
tell what the button should say. 64
It could say, okay, it could say submit in this case, but whatever it is you want the button to say, 65
you would add it to the "value" attribute. 66
If this HTML was displayed in a browser, then this is what you would see. 67
This part is the first label in this form. 68
This part is the first text input. 69
This is the next label, and this is the next input. 70
These are all text inputs and they will expect a value in there. 71
And then finally we have our submit button, which is also an input, but it has the value of submit, 72
which is what we assigned over here. 73
So HTML forms are pretty simple and you'll get used to this format pretty soon. 74
But the important thing is how do we incorporate this form into our backend? 75
So I want you to go ahead and download the exercise 3.4 Middleware.zip from this current lesson, 76
so in the course resources for this lesson. And then once you've downloaded and extracted it, you 77
will see that it has a bunch of files already in there. 78
As always, the first thing we're going to do is to cd over into this new folder and then run npm install 79
so that everything that's inside the package.json or the dependencies gets installed. 80
Now notice the difference in this particular project. 81
I've actually got a public folder and the public folder usually is the place where we put our static 82
files such as our HTML files, CSS files, images, things that don't really change and don't need to 83
be acted upon. 84
What we're going to do is we're going to try and render this index.html as the thing that we're going 85
to return from our server. 86
Previously, you've seen res.send, but in this case, I'm actually using a different express method which 87
is called res.sendFile. 88
Now res.sendFile requires an exact path in order to know which file to send back. 89
Now of course, the file that we want to send back over to the client is our index.html. 90
In order to get the full path of that particular file, we need to do a little bit more. 91
When your server is hosted on a cloud computer, when it's no longer locally hosted, as is the case 92
for most servers, then in order to figure out this directory name where the file lives in, it takes 93
a little bit of work. 94
And these are the lines of code that are required for this. 95
So firstly, we're going to import something called dirname directory name from the "path" module that's 96
bundled with Node, and then we're going to do a little bit of conversion in order to eventually end 97
up with this constant called directory name, which basically is all of the path up until the path that 98
we want to access. 99
In my case, it could be my Mac, and then it would be my username, and then it would be the Web Development 100
folder and so on and so forth. 101
And it's going to be able to figure all of that out just by using these three lines of code. 102
And this also means that you don't have to type out the exact path, right? 103
Because when it is true for local development, such as the path at the moment, once we've actually 104
put our server up into the cloud and host it somewhere, then that's no longer going to be the file 105
path. 106
So we need to figure it out dynamically and this is probably one of the best ways to do it using Node 107
and Express. If I go ahead and console log this, 108
directory name, plus the location of my file, 109
you'll see that if we go ahead and use nodemon and then run index1.js, 110
you can see that if I hit up the GET route, so I'm just going to use Postman to do that, to hit up localhost: 111
3000. 112
You can see it's going into 113
Users/angelayu/ Web Development Projects, but this entire directory path was generated using these three lines of code and 114
your path will of course be different depending on whether if you're on Windows or Linux or Mac. 115
And once your project is hosted somewhere online, then that will be relative to the computer that it's 116
hosted on. 117
Now that we've seen that, let's go ahead and delete this and let's test this out to see if we can actually 118
see that index.html page being sent over when we make a GET request to the home page. In order to do 119
that, let's make sure first that our server is up and running, which it is, "Listening on port 3000". 120
And then let's go ahead to our localhost:3000 and you can see that this HTML page is coming from over 121
here, 122
h1 Band Name Generator. 123
There's a form with a label for street name, a label for pet name, 124
and this is basically the exercise that we're going to compete by the end of this lesson. 125
But you can see that in this case, I'm not just sending over a little bit of HTML when I do the res.send, 126
instead, I'm sending over an entire file that I've linked to. 127
So now that we've figured out the first part, let's go ahead into the main topic of today's lesson, 128
which is how to use middleware, right? 129
And the middleware that I want you to use, which is something that you will use again and again and 130
again, is called Body Parser. 131
We're going to go ahead and install body-parser and then we're going to use body-parser in order to 132
parse the information that's coming in through the form on our website. 133
So remember, this is our index.html page and when this "submit" button is pressed, what's going to happen 134
is that form is going to make that POST request to the path that we specified, which is 135
/submit. 136
So what we need to do is to have a route handler that is able to handle a POST request to that particular 137
path. 138
And then we're going to use body-parser, which we're going to install very soon, and then we're going 139
to use it as a piece of middleware in order to parse the information that comes in from the form. 140
So from this HTML form. 141
And then we're going to add that data to the request object so that we can actually console log it under 142
req.body. 143
This is the goal and this is the code that's required to do it. 144
If you look inside the index1.js file, that is basically our starting point for adding this 145
body-parser middleware. 146
I want you to go ahead and use the code that you see here. 147
So pause this video at this point and I want you to implement this code so that it actually works live 148
on your end. 149
So you should be able to go to localhost and type something into the street and pet fields and hit submit 150
and then see what you typed into the form in your console log. 151
Pause the video and give this a go. 152
All right, so let's run through this together. 153
So firstly, making sure that we're inside index1.js because there are many sub-parts to this 154
coding exercise 155
in this lesson. We're going to go ahead and stop our server to npm install the body-parser module. 156
Now this is just so that you know where that body-parser comes from because of course if you look inside 157
the package.json, I've actually already got it set as a dependency, but when you're creating this 158
from scratch, you will need to install the body-parser module. 159
Once we've done that, let's go ahead and import body-parser into our index1.js. So now we can 160
use it and we're going to add this as a middleware by using the use method. 161
This method gets called before any of the route handlers. 162
Once we've got the use method, then we can add in our middleware function, which in our case is called 163
body-parser. 164
Now in order to use body-parser, we need to tell it what kind of data we want to parse. 165
And in our case, because we're dealing with a HTML form, we want to choose the URL encoded method. 166
Inside here, 167
there is one obligatory option that we have to set, which is this option called "extended", and you 168
can set that as true or you can set that as false, 169
and it basically just determines what is being used behind the scenes to parse the data that's coming 170
in. 171
And in pretty much 100% of the times, this is a line of code that you're going to write. 172
And once you've done that, then we get an extra power using this middleware in the sense that every 173
single request object now has a body. 174
Whereas before, without this, if you try to tap into req.body, you'll get undefined. 175
There's just nothing there. 176
But now with this body-parser parsing information coming in, we can in fact access it. 177
Now the place we want to access it is not going to be in the GET because the GET handler is just meant 178
to send back a resource that the user wants. 179
It's not meant to really deal with things coming in. 180
So instead we're going to create an app.post() method and we're going to hit up the route that the 181
form is going to send and act on, which is /submit. 182
So let's make sure that those two bits match in terms of capitalizing and also the whole spelling and 183
everything. 184
And then next we've got our request, response (req, res) and then our anonymous function, and we're going to go ahead 185
and console log the req.body object. 186
So now that we have req.body, we can send something to our server and see what information 187
we get. 188
So I'm going to use Nodemon and hit up our index1.js, and now we can go into Postman and go into 189
the localhost:3000/submit as our route. Making sure it's selected as POST and then under 190
this tab called body, this is where we can simulate a form. 191
So make sure the x-www-form-urlencoded option is selected because that's what we are handling. 192
And then go ahead and add in some pieces of data and you can add whichever key value pairs you want. 193
Once I go ahead and hit Send, you'll see that console log being enacted upon because we hit up the 194
POST route and I'm getting those key / value pairs being printed in here. 195
Now, if I go ahead and stop using body-parser as my middleware and I try that again, then you can 196
see that I'm getting undefined. 197
There is no body to my request. 198
So let's enable that once more. 199
And this time we're going to hit up the POST request from our HTML form here. 200
Our Band Name Generator is a very simple website that takes the street name that you grew up on, which 201
in my case was Aberdeen Road, and then your pet name, which in my case was a rabbit that I very creatively 202
called rabbit. 203
And then once I hit submit, it's actually going to make that request, which is the POST request to 204
the route that's /submit. 205
And when we take a look down here, you can see it has encoded this first part, which corresponds to 206
the name of that input. 207
And the second part is the value that was placed inside that input, which I wrote as "Aberdeen". 208
And it's the same for the next input as well. 209
That's the superpower that we managed to gain using the body-parser middleware. 210
In the next lesson, we'll learn to use another popular middleware package as well as learn how to write 211
our own custom middleware with Express.js. 212
So for all of that and more, I'll see you on the next lesson.