Hey, guys.
In today's lesson, we're going to be learning all about HTTP requests and we're going to learn the
language that allows you to make requests to your Node server.
What exactly is HTTP and what does it stand for?
Well, the first part you already know because it stands for HyperText, just like HTML stands for hypertext.
The second part, the Transfer Protocol basically describes this as a language, a language that allows
computers to talk to each other across the Internet.
We as humans, when we want to transfer our thoughts between each other, we have this thing called
language,
or you could call it thought transfer protocol.
It could be English, it could be French, it could be Spanish,
but either way, we make these sounds across the air and we allow each other to understand our own thoughts.
Now, when computers want to talk to each other across the Internet, they need the Hyper Text Transfer
Protocol, a different language that allows them to understand each other.
Now I want to teach you some basic vocabulary to get you started with the computer language of HTTP.
Just as always, when I go to a new country, I always learn a few words just to ensure that I don't
go hungry.
So in China, maybe you can say, Wǒ èle, maybe in Japan, you'll say Onaka ga suita,
and if you go to Mexico and you want some empanadas, you'll say Tengo hambre, and so on and so forth.
Basically, we want to know enough vocabulary in HTTP so that we know what's going on in the secret
lives of computers.
When we make these HTTP requests, there are five main words that you'll come across and it's GET, POST,
PUT, PATCH and DELETE.
So let's go through each of them.
Now remember previously when we tried to run our server and request our website from the server, we
got an error saying Cannot GET. GET is one of the first words you're going to need to learn,
and this is when you want to request a resource from the server.
This could be an HTML website, it could be some piece of text, it could be a piece of data from the database
or the server,
but you are "getting" something from the server when you make your HTTP request using the GET keyword.
Now, POST is similarly easy to understand.
Essentially, in this case, what you're doing is you are sending a resource to the server.
This could be a piece of information like if you have a Form to sign up to your website. Well, their
email and their password is going to be sent to your server when they click that Sign-up button
and that is going to be done using a POST request.
And then on the server side, you can take that information and then do whatever you will with it,
save it into a database, or process it or work with it somehow. PUT and PATCH are somewhat related because
essentially what they are is they are update methods.
However, they are a little bit different. Now, a put request is when you want to replace a resource
with whatever it is you're sending over.
So you want to update something by replacing it completely.
PATCH is a little bit different and similar to the word in English,
essentially you want to patch-up a resource even though both of these are updates, they work a little
bit differently.
And a good analogy for the difference between these two types of update, which I often like to think
about, is an Amazon return.
I order a lot of parcels from Amazon and very often I get things which are broken or something that's
not working.
So let's say you get a bicycle from Amazon and when you receive it, unfortunately one of the tires
is just broken.
Now this is real story.
I actually ordered a bicycle from Amazon.
Don't ask me why.
Now, when you tell Amazon that you have shipped me a broken bicycle, they have two options.
Option Number 1 is they use a PUT request to give you an entirely new bicycle.
They just replace your bicycle with a new bicycle
and this way you update the bicycle.
Now, the other option they have is a PATCH request, where in this case they only send you the functioning
wheel so that you yourself can replace the broken wheel with this new functioning wheel and you patch
up the broken bicycle.
Finally, we have the DELETE word, which is pretty easy to understand.
It just deletes resources,
either from the server or from the database,
but essentially, this is a request from the client-side computer to the server-side computer saying that
there is something that needs to be deleted.
With these five words under your belt, you should be able to navigate the world of HTTP requests.
Let's take a look at this with a real example.
Here I've got a server created using Node and Express, and as you've seen before, we are running this
server on port 3000 and it's up and running.
As you saw before, when we run this code and we tried to load up the website at that location, localhost
port 3000, we get this error saying Cannot GET.
So now that we know what GET means, it means you, the client using the browser are trying to get a
resource, namely the homepage to load up,
but you Cannot GET because our server does not yet have any code that allows us to do that.
So what do we have to do instead?
Well, we need to add a little bit of code to say, well, what should happen when a user is trying
to get at our home page?
So the forward slash (/) goes at the end of the home page.
So for example, if you have localhost:3000 and then at the end you can have a forward slash or
you can have no forward slash,
but either way, when you load this address up, it's trying to make a GET request to the root, which
is the home page.
In this case, we've added the Express method called GET
so now our server knows what to do when that GET request comes through,
and then in between the curly braces of the anonymous function right here, we can define how our server
wants to respond to that GET request.
And in this case, I'm just sending over the words, "Hello World."
And so now when we try to load up our home page at localhost:3000 with this updated code, you will
actually see the words, "Hello World" come up in the browser.
Let's have a little bit of practice doing this and also setting up our server.
First, I want you to just simply repeat the process that we did in the previous lesson, which is to
set up a brand new server using Node and Express, and because it involves quite a few steps, I've
listed them all out here for you 1 to 6 so you can keep the screen up somewhere and pause the video
and then try to complete the exercise by creating your own Node server using Express and following these
steps.
Now, you don't have to write the GET request yet, just the parts where you can get your server up and
running.
Pause the video and give this challenge a go.
All right.
So the first thing we want to do is to create a new folder in our Backend module called, 3.2 HTTP Requests.
Now you can either do this using VS Code buttons or you can do this using the mkdir command,
but either way, we want to create our new directory and then inside we're going to create an index.js
file.
The next thing we're going to do is to go ahead and initialize NPM in this project folder.
So first we need to cd over into the right directory.
So I'm just going to do that by dragging over this folder here 3.2 HTTP Requests.
Once we've made sure we're in the right location, then we can go ahead and use, "npm init -y" to set up NPM
on that directory.
And next we can go ahead and install Express by using,
"npm i express".
Now once those modules are installed, we're ready to start writing some code.
So the first thing we're going to do is we're going to import express from "express" and remember that
in order to use import, we have to go into the package.json and change the type of our project to use
modules from ES6.
So let's hit Save, close that down.
And now we've imported Express, we can create a const, which is our app, and we can do that using
Express.
Now, we're able to start listening with our app using app.listen() and then we provide the port that we
want to listen on, which I'm going to set to 3000 as always.
And then we can add an anonymous function to specify what should happen when our port is up and running.
And all I want to do is just simply console.log() that the "Server has started on port..." and then I'm just
going to insert my port number right here.
All right, that's it.
And now we're ready to go ahead and run our server so we can use Node and then index.js and our server
has started.
And that concludes the challenge.
This is how far we got in the previous lessons similar to previously, though we get that error where
it says Cannot GET / the forward slash location.
Now if we go back and we add the code that allows our server to handle GET requests, then we can fix
that.
So we're going to use the app.get() method, which comes from Express, and then the path or the endpoint
that we want to be able to handle right now is just the root, the home page, which is just a forward
slash (/).
Now next comes an anonymous function and, and we can tap into the request and response.
So it's written usually like this req and res and inside the curly braces, we can define what we should
do once we receive this GET request at this endpoint.
Firstly, the thing I want to show you is what the request from the browser looks like.
We can go ahead and log the request parameter right here.
And if I go ahead and hit Save, stop my server, and restart my server, remember that when we're using
Node to run our index.js file and get our server started, every single time we make a change, we have
to stop the server using control C (Ctrl + C) and then restart the server using node index.js.
This brings me to a point where a lot of people fall down on if you have a server that has started and
it's running somewhere, but then you decide that you open up another terminal somewhere else,
and then you try and run another project.
So in here, if I try to run Node index.js again, I get this error where it says, "address is already
in use..." and it tells me that I'm trying to run my server on a port, port 3000, which is already running
something.
It's already occupied.
This is one thing that's really important to note and when you see this error which you might encounter
from time to time, just know that you can solve this in two ways.
One is you can go to the place where you have the server running and you can stop it and then go back
and you can run your other project without any problems, as you can see right here.
Another way you can do this is by actually killing that particular port using a terminal command.
Now I'm going to link to this blog post, which shows you which commands you need to use in order to
close a port on Mac, on Windows and on Linux.
So basically you can follow the process here
if you get really stuck and you end up in that situation where you can't find the place where you've
started your port in order to stop it.
Now, let's make sure that our server is started and go over to localhost:3000 and then over here we can
see the printed output of what that entire request from my browser actually looks like.
Now there's actually way too much information to process here, so I'm going to narrow it down by going
to request.rawHeaders.
And the raw headers are basically a list of key/value pairs that come from where the request originated.
Let's hit Save.
Let's stop our server using Ctrl C.
Let's restart our server using, "node index.js".
And now if we request this again, then you can see these are the raw headers that we're getting.
So it tells me where is the domain, where this website is being accessed.
It tells me other things, such as where that request originated from, which in my case was Google
Chrome, what system I'm running, and a whole bunch of other things about my request.
That's essentially what a request is.
It comes in from the browser, it hits up a particular path, and then we can either get hold of it
inside this anonymous function or more importantly, we want to be able to send back a response.
To do that, we use res.send,
and in the body of this method we can send back a piece of text.
So for example, I am just going to write, "Hello World," that's it.
And then I'm going to hit Save.
I'm going to go ahead and stop my browser, rerun my browser, go back and reload, and you can see
now instead of having that error, Cannot GET root path, I've now got, "Hello world" being sent back from
my server.
So when I request my home page at this particular path and I hit Enter to go to that location, my browser
sends the request to my server and because my server is running and listening and it knows how to handle
that GET request, it sends this piece of text back,
and that's what I see on this web page.
That's the entire simple process of what's going on behind the scenes.
So one thing you've noticed is every time I've changed any sort of code on my server side, I've had
to stop my server and then restart my server, which frankly is a bit of a pain.
What can we do instead?
Well, professional Node Developers use a tool called Nodemon, and what Nodemon does is pretty simple.
It automatically restarts the node application when it detects files changes.
That means that you don't have to manually stop and start your server every time there's a change,
Nodemon does that for you and to use it.
It's as simple as replacing the node keyword with nodemon and then the file that you want to run and
it's going to automatically do all of the monitoring magic behind the scenes.
In order to test this out, I want to show you one other thing that you can send.
Instead of just plain text, you can also send fully formatted HTML.
So, for example, in this case, I'm not sending back text.
I'm actually sending back in the form of an h1.
Going back to our project, let's go ahead and stop our server and let's use npm to install using the
-g flag so you can use npm i or npm install.
I is probably better to prevent making typos and then the -g flag stands for global.
So this means that we are installing this package called nodemon globally on our computer because we
don't just want it to work for this one project, we'll want to use it for other projects that we develop
in the future as well.
So we're installing it for use on any project using that -g flag.
So now let's go ahead and hit Enter and install it.
Now if you get some errors or your install didn't really work, go ahead to the Nodemon documentation
and simply copy and paste the installation command.
Now, once the installation has completed, then we can now use it by typing "nodemon" and then "index.js"
to use Nodemon to run our index.js path to monitor our files for any changes.
And I'm going to make that change right now.
Instead of sending "Hello world", I'm going to send an h1 that just says, "Hello".
Now when I hit Save or even if I don't hit save, Nodemon is actually already monitoring those changes
on a timely basis and it has restarted my server because it saw those changes.
So now let's go back to our localhost.
Let's refresh our page.
You can see that has now been updated and my server is now sending back fully formatted HTML.
You saw that previously we were only handling the endpoint.
That is just the forward slash (/),
and I want to talk a little bit more about what endpoints are.
If you imagine that you want to send a letter to your friend somewhere across the world, let's say,
you have a Pen pal in Europe or you have a Pen pal in Africa,
then the endpoint of your letter in HTTP would be forward slash that destination.
So it could be /Europe or f/Africa,
and these would be the endpoints for your letters.
Now, when you send your letter, that's equivalent to your HTTP request.
We saw that we can get hold of the root or the home page by targeting the forward-slash (/) endpoint,
and this is equivalent to going to localhost
:3000 and then hitting a forward slash or not having the forward slash,
either way, it's going to hit up this particular root. If we want to add other endpoints into our server
code so we can handle more situations then we simply just need to add another GET method.
So in this case, I'm adding the endpoint "/About", and when the user tries to hit up that
endpoint, they're going to get this h1 instead. When they go to Localhost
:3000,
and this is kind of equivalent to when you go to say, www.google.com, which is the main domain,
and then you hit up the, "/About" endpoint and this then gets picked up in our server right
here and these lines of code get triggered, which is why this h1 gets displayed on the screen.
We're going to try this out in our exercise so that instead of just writing a server that runs, we're
going to add to this exercise so that our server can handle the, "/", "/contact"
and "/about" endpoints. It's totally up to you what you want your server to send back on
the home endpoint.
So this could be maybe just say, Home Page as a h1 and then maybe on the /contact route,
maybe you could have your phone number being listed,
etcetera.
And on the /about endpoint, you could maybe have some info about yourself, maybe a paragraph element
or an h1 or something like that.
It's totally up to you how you want to do it.
It doesn't really matter as long as you're able to understand how to hit up the different endpoints
and how to target them in your server.
Pause the video and complete this challenge.
All right.
So this is pretty simple all I'm going to do is copy this part of my code.
The get() method and paste it twice so that I get two more endpoints that I can add.
So the first one is the about endpoint, and in my case, I'm just going to write an h1 called, "About
me."
And then maybe I can also have a paragraph tag saying, "My name is Angela," close my paragraph tag.
That's all the HTML that I'm going to send over.
And then the third endpoint is the contact endpoint.
And in this case, I'm going to have a h1 that says, "Contact me," and I'm going to have a paragraph that
says maybe my phone number is +4412345678
9
And then let's close off our paragraph tag and notice how Nodemon is working hard in the background,
noticing these changes and updating and restarting our server so we can simply go back over to our localhost
3000,
refresh the page,
this is what our home page looks like, this is what our about page looks like, and this is what our
contact page look like.
So you can see how we can use these different endpoints to plan for when a user or when a client tries
to hit up that endpoint.
And in reality, what this means is we can easily build multi-page websites, navigation into our web
apps built using Node and Express on the backend.
So in the next lesson, we're going to be learning more about different types of HTTP requests, and
we're also going to be learning how we can use Middleware with Express.
So for all of that and more, I'll see you on the next lesson.