Node.js Crash Course Tutorial #6 - Express Apps

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
a rather than gang so now we know how to install packages I'd like to install one called Express for our project but before we do that let's just quickly talk about what Express is and why we'd use it so currently we've written all of this code right here to serve up a few different HTML pages and that's fine in this case this really wasn't that hard to do but if we start adding more complex routes or handling post requests from forms and generally adding more server-side logic then it will get quite messy in quite hard to organized now Express is a framework that helps us to easily manage our routing requests server-side logic and responses in a much much more elegant way and it makes our code easier to read and update and extend now you don't have to use Express you can do everything using raw node as we have been doing so far but Express is really good it saves us time allows us to write clean code and it comes with some extra features that really really help us out so I'm just here on the Express page on the NPM website and down here we can see first of all how to install it we're going to do that in a second but also quickly how to use it as well so we basically set up an Express app and then from there we can set up some routing so this one right here is in its simplest form it's responding to any kind of get request which is the kind of request we've been making when we've been putting some kind of URL up here in the address bar and this is responding to get requests to just forward slash and we're doing that or right here yep and all this is doing is taken in a callback function and it's sending a response so it's quite similar but as we add more routes you're gonna see that this becomes much easier than handling routes this way okay so let's install it first of all NPM install Express that's what we need to do so open up your terminal and I'm going to cancel out of this process then say NPM install Express like so and that should add it to your dependencies remember if you're using an old version of node use the save flag which is double - save at the end of that and it's going to save it to your dependencies or right here we can see Express has been added okay then so now we have Express installed let's go ahead and create an Express app now to do this I'm going to create a new file I will keep this server file here in case we want to compare the code between the two files later on but I'm going to create a new file for our Express up and typically people call this file up jeaious like so so in here the first thing we need to do is actually require Express so I'm gonna say Const Express equals a require Express okay so now we've required that we need to set up an Express app and that is really simple to do all we need to say is Const app and set it equal to Express and then invoke that so this right here returns a function and we're storing that in Express and all we're doing is invoking that function to create an instance of an Express at which we're storing in this constant you can call this constant what you want but you know commonly people call it up alright then so the next thing we need to do is actually listen for requests so much like we did over here when we listened to port 3000 we need to do a similar thing over here so I'm going to say listen for requests and underneath that I'm going to say app listen and then we want to listen to port 3000 now automatically it infers that we want to use a local host so we don't need to add anything else now this also returns us an instance of the server much like this does over here when we create the server and we could store it in a constants in case we want to reuse that server later on for something else like WebSockets but you don't need to and I'm not going to do that for the sake of this tutorial either all right so we've set up an Express app and we're now listening for requests at port 3000 now how do we actually respond to those requests well all we need to do is say app and then if you want to listen for a get request we can use the dot get method and this takes in two arguments the first argument is what path or URL you want to listen to so if you want to listen for forward slash about and respond to that you just put in forward slash about much like we did that for this case over here now I just want to listen for requests to just /so the root of the domain if you like now the second argument is a function and this function takes in a request and response object so that we can do something with those so again this contains information about the request such as the URL and the method of the request like get or post or something else and then this right here this is the response object which we can use to send a response now if you want to send a response we can do the same thing as before where we said things like response dots rights and then we can write some HTML and then we say response dot and but instead if you want to you can use a third method now now that we're using express and that is called response dot send and the good thing about this method is that first of all it infers the type of content that we're trying to send to the browser and it automatically sets the content type header so this line of code over here we don't need to do anymore because Express automatically works that out for us dependent on the type of content we send but another benefit of this is that it also infers the status code so we don't need to manually set that the rubber case is why we do want to manually set that but a lot of the time is going to set it for us in this case it's gonna be 200 if we're sending back some HTML so let's just send back a bit of HTML I'm going to say P tag right here homepage and then close that off so now we need to run this file app KS instead of server KS so let me do that I'm going to say no daman and this time up and that's going to run this file and then now if we go to just forward slash we should see this response so let's try that so localhost 3000 forward slash and we see homepage and if we inspect that we can see inside a P tag now if I go to the network tab and I'm going to refresh so we can see this requests a local host that we sent we can see that the status code is 200 and also the content type has been automatically set to text HTML because you figured out that that's what we're sending right here so that my friends is how easy it is to respond to a specific URL now we do actually want to respond to several different URLs like we did over here like forward slash about for example and we're going to do that going forward and we're going to actually send back some HTML pages instead of just a string of HTML as well okaythis so we've seen how to respond to this single get request for forward slash but if we go to any other kind of URL like forward slash about then we don't get a page back and that's because we don't have a route handler settle for that URL so we can do that by just adding multiple of these different gets handlers so I'm going to do that by copying this dude and pasting it right down here and this time we want to respond to a get request at the URL forward slash about and then we could just change this to about page and there we have it that's how simple it is we've responded to two different routes now so if I go to the browser again and go to forward slash about I should see about page and if I just go to /ic homepage now that's okay but again this isn't a great way to send HTML to the browser ideally we want to send an HTML file so we can keep all of our HTML in separate files now we already made all of those files over here we have an about and index and a 404 page so we just want to send those back to the browser so how do we do that with Express well dead simply well let me first of all comment out these two things right here and then for just forward slash we want to send back the index page so we can say response dot send file and then right here we need a path to that file so dot forward slash into the views folder then forward slash again index dot HTML now there is a slight problem with this this path right here is not meant to be a relative path or rather if it is a relative path we need to tell Express where is it relative from because by default is going to look for an absolute path the path from the root of our computer so what we need to do here is pass a second parameter or second argument which is an object an options object and we can specify what the route should be what is this a relative to now this is just going to be the root of the project which is this node crash course and it's the same directory that this app.js file is in now we know how to get the core directory we can do that using underscore underscore do name that gets us the directory that we're currently in inside this file so now we've said that the routes should be this folder Nord crest course and then from there this can be a relative path so inside the project folder then we go into the views folder and then we get indexed or HTML okay so another way of doing this would be to use the path module which is a core module in node to join together the der named way that the file path but for now we're just going to use this way so let me save that and in fact we'll do the same thing for the about handle it down here so let's copy that and paste it right here and change this to about dot HTML instead okay so now if we go to just forward slash we're sending back this file and if we go to forward slash about sending back this file okay so let me save it and preview if i refresh over here we'll get the on page and if I go to forward slash about we should get the about page which we do so let me just quickly go to these different HTML pages and what I'd like to do is just add in a little nav so we can link to one page from another so I'm gonna do that underneath the h2 over here do enough and inside two links so one for the home page which is just forward slash and one for forward slash about and I'm gonna do the same thing for the about file over here just so that we don't have to keep on typing out the address up in the address bar at the top and we can just click on one of these links on either of those pages so let me cross that off and the refresh over here and now we can see home page and about page and now we can just click on those just makes it a bit easier to test those two different routes so previously we saw how to do a redirect without Express over here in the server Jas code and already it was much a case against a specific URL we set the status code and then we set a header which was the location and that meant that the browser would relocate to forward slash about and then we ended the response so that redirected the user to the forward slash about routes so how do we do something similar in Express well it's really easy all we need to do is create another get handler for the URL that we want to redirect first of all so let's say app get and say we want to redirect users that go to file / about - us so we're going to match against this URL then we fire a function when a request for this URL comes in so request our response would get access to those objects inside this function and all we do now is say response dots redirect and where do we want to redirect to well just forward slash about and that is all there is to it and under the hood express sends this response to the browser and forces it into a new request for forward slash about and it also automatically sets the status code so we don't have to redo this so let me now save this and make sure we're running this server we are doing so let me now preview this in the browser and go to this thing over here so if we go to forward slash about us then we can see now we get the about page all right so now this is working dead simple to do okay so we also saw previously that we could set up a 404 page and we did that by just having a default case down here which amended to the path 404 to HTML we set the status code and then we sent back to that file so we can do a 404 in express really easily as well and the way we do it is by saying app and then this time we use a method called use now we use this method use to create middleware and fire middleware functions in Express now we're going to learn much more about use and middleware later on but for now let me just flesh this out and then I'm going to explain it so inside here we fire a callback function and this function also has access to the request and the response objects now if someone goes to the wrong URL ultimately what we want to do is set the status code to 404 and also send a file which is this thing for a for to the browser so let's say response dot send file first of all we've seen this up here and we're going to do the same thing so let's just copy it those two arguments and paste them all right down here and change this to 404 so that is going to send this 404 page to the browser now then how is this working well the use function is going to fire for every single request coming in but only if the request reaches this point in the code so when we send a request in the browser if we type something up a and hit enter that express is going to run through this code top to bottom and it's going to look at each one of these gets handlers and if it finds a match if the URL that a user has requested is matched against this thing right here if Phi is that callback function if it doesn't match it carries on down the file now if it matches if inside we send the response to the browser like this then Express no longer carries on down the rest of the code so none of the other functions will ever find if they match as well because we've sent a response now now if we don't match then it's going to carry on to this if we match it's going to send a response if we don't match then it's going to carry on to this etc down the page now if we get to the bottom at this point or right here if by this point there's not been a match then it will go ahead and fire this function because this use method basically just says use this function for every incoming request it's not scoped out to a particular URL you know something that we could type in here like in the other ones over here it's actually going to fire for every single request regardless of the URL if the code reaches this point if we don't have a match up to here at this point we're sending this 404 page to the browser so let me just save this and test it out first of all and we're gonna go to forward slash then a lot of garbage press enter and we get the 404 page this works now the position of this is important it must go at the bottom over here because if it went somewhere near the top up here above for example the bounce handler then what's gonna happen is if we go to /a bounce over here the request is going to come in express is going to go through these handlers well it doesn't match this one so I'm going to carry on down here and it gets to this and it fires it because this is not scoped to a particular URL it fires for every single request so it fires this function and we send a response to the browser and remember we said if we send the response to the browser then it doesn't carry on with the rest of the code so it's never even gonna reach this about handler so let me demo that I'm gonna go to forward slash about and we'll probably get this page this 404 page which we do so that is why this should go at the very bottom over here so that it's like a catch-all if nothing else matches then we're gonna send this 404 page to the browser now that the minute Express doesn't realize that this is actually any kind of error and that we're sending a 404 page it's not going to look at this HTML file and say oh oh I'm going to guess that this is actually 404 error it doesn't do that we have to in this case manually set a 404 error so to do that we can tack on the status method to the response right here and type in the status code for a4 and then we can just tack on this to the end as well we can chain it on because this method right here returns the response object itself so we can just tack on that method at the end of it and that still sends the file for us only this time we've edited the status code to be four or four so if I save that let's just check everything still works blardy blardy blar hit enter and it does awesome so we know now how to set up an express up how to set up different route handlers redirects and a 404 as well as well as how to send back an HTML file as a response to the browser now let's just quickly compare this code right here that we have to this old code server KS and I think you'll agree that this old code right here looks a lot more complex less readable it would be harder to maintain and add to I think than this code right here it looks a lot more elegant we have our own function for each individual route where we can nest our own logic for each route we can easily do redirects easily do 404s I think this is a lot more elegant so I'm going to actually delete this server file because we're not going to use that going forward instead we're going to stick with Express and this app.js file for future lessons and next up we're going to be looking at an alternative to HTML files whereby we can inject dynamic data and content into our different templates using a view engine
Info
Channel: The Net Ninja
Views: 86,067
Rating: undefined out of 5
Keywords: node.js, node, node js, node.js tutorial, node tutorial, node js tutorial, node crash course, node.js crash couse, node js crash course, crash course, tutorial, install node js, install, node.js introduction, what is node.js, what is node js, what is node, node vs deno, node express, node.js express, node and express, express tutorial, node vs express, express, express app, express crash course, node express tutorial
Id: Lr9WUkeYSA8
Channel Id: undefined
Length: 19min 8sec (1148 seconds)
Published: Fri Jun 19 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.