Node.js Crash Course Tutorial #4 - Requests & Responses

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
alright then gang so now we've created our server right here and we say we want the server to listen to port 3000 on localhost so when we send requests to this localhost port 3000 then we should fire this function right here now first of all we need to actually run our file for this to work so let me do that again node server and now we're listening for request and port 3,000 so if I go over here and refresh this then we should see down here request made because this function logs that to the console now what if we make a change to this what if instead we want to log out for example the request object and the request object contains information about the request that a user sends so let me do that let me delete this and instead log out the request object and I've saved that and now I'm going to go to the browser stop this and refresh come over here and we don't see the request object log to the console we just see request made and that's because every time we make a change we have to restart our file it's still running the old file and it's not picked up the code change so I need to exit out of this process by clicking on the terminal then pressing ctrl + C and that exits out of the process now I can run this again by saying node server like so and now we're listening again for requests on port 3000 this time it will log up the request the latest code changes so if I press ENTER over here and we should see the request object now it's a huge object with loads of different things on the request object it contains headers which is metadata about the request the type of request the expected response types etc it also contains the URL that a user has visited up here it contains loads of other stuff as well for now let me just log out a few different things from this so I'm gonna say for example the request or URL and also the request dots method so that is the type of request is it a get request to post request etc so let me save this we have to restart the server so I've cancelled out the pros by clicking ctrl C then I'm gonna say node server to run this again and if I come over here and I already flesh then over here we can see that this is the URL it doesn't say localhost port 3000 it's just from the points after that so in our case is just /the roots of the website if you like and the method is a get request so if I try something else if I go to for example /a bounce then we should see that it is still a get request but this time the URL is forward slash about and this information about the URL is going to be really helpful later when we come to send some responses because we want to send back a different response dependent on that routes if they go to just forward slash we want to send back an index page or home page if they go to forward slash about we might want to send back an about page so we can use that information this thing right here later on when we come to implement some kind of simple or routing and we will see that but first of all let's also take a look at this thing right here the response object so then we also have access to this response object right here which is what we use to send a response to the browser now at the minute we're not doing that which leaves the browser hanging around just kind of twiddling its thumbs doing nothing so we want to formulate some kind of response now the first step in doing this is to formulate the response headers so response headers give the browser a little bit more information about what kind of response is coming back to it for example what type of data we're sending back is it text HTML Jason etc and we can also use the response headers to do things like set cookies so let's do that first of all I'm going to do a little comment that says set header content type like so and the way we set a header is by using the response object and then using the method set header like so now we want to set the content type header there's lots of different types of headers and I'm going to show you a couple in a second but I'm going to say the content type and this could be either text or it could be HTML or it could be Jason like I said we're going to say for now we're going to use text forward slash plain and that just means we're sending back some plain text to the browser so how do we actually send that data back to the browser well again we use the response object and we use the write method to write to the response and let's say for example I just want to say hello ninjas and send that text back to the browser well I'm writing to the response but now we have to end the response to say okay we've ended this now send it back to the browser so we do that by saying response dot end so three steps first of all we're setting the header for the content tank being sent back to the browser then we're writing whatever content we want to send back to the browser then were ending the response which then sends it to the browser so if I save this I need to come down here and cancel out of this process and run node server again then I'm going to just refresh over here and we should see hello ninjas this text right here let me zoom in a little bit okay so let me just inspect the element right here and then go to the network tab I'm going to refresh so we can see this request down here this is the request we've made up here now if I click on this we can see the headers right here the response headers are right here and you can see this is the one that we've set the content type but we also have these ones automatically set as well now they're out or the response headers that we can set manually and we might see some of them later on but for now this is enough so what if I want to send back some HTML instead of just plain text well the first thing would be to change this to text forward slash HTML and then instead of just sending a normal string back we can send back an HTML string so I could say P tag right here and close the P tag right there also if I wanted to add another line of code I could do let me just duplicate this and say hello again ninjas so first we write the first line of HTML to the response then we add another line of HTML and it writes both of those one after the other then we end the response which sends all of the resulting code back to the browser so again let me save that I'm going to cancel out of this process run it again and then if i refresh over here we should see hello ninjas hello again ninjas and if I inspect we should see that those are in paragraph tags now notice the browser has automatically added the HTML head and the body tags but if we were to write our own right here then it would replace those and let me just demo that if I just say up here response dot right and then inside here I'm just going to do for example a head tag and a closing head and inside that we'll just do a link tag like so and this is going to be rel equals stylesheet it doesn't really need to go anywhere at the minute but we'll say href is equal to just a hush okay just to demo that this gets added to the document okay so if I save this now and go over here and refresh in fact we need to cancel out the process or run it again and by the way we will learn an easy way to do all this so we don't have to keep canceling out the process and running it again later on in the course if i refresh now by the way we can open the head and we can see that that link tag is right there so if we create our own and write that to the response it replaces the default one for us okay so this is how easy it is to actually send a response but you can already see that this is looking quite messy if we want to send some HTML back and this is just some very very very simple HTML I imagine your web pages are going to consist of more than two lines of text so this really is probably a bad way to send back HTML because it could get really messy if we add a lot more ideally our HTML pages should be created in a separate tml file and then node could maybe read those files and send them back to the browser and to do this we're going to need to make use of the file system again alright then so we've seen how to send HTML this way but let's see how we can actually send a full HTML page a full document to the browser instead which is a little bit cleaner so the first thing I'm gonna do is create a new folder over here and I'm gonna call that views and this is where I'm gonna store all my HTML so inside there I'm going to create an index.html file and this is what I want to send back to the browser now I'm just gonna paste this code in so you don't have to watch me type it all out I've just copied it from my github repo for this lesson and it's just a simple head with a title right here and a body and h1 and also an h2 so that's the HTML page I want to now send back to the browser when a user sends a request so let me get rid of all this stuff here we don't want to do it that way anymore we still want to set the header to be of content type text forward slash HTML but this time we want to send back a file or rather read a file and then send the data from that file as a response to the browser now we've already seen how we can read files we do that using the court node module FS so let's require that first of all at the top I'm going to say kant's FS is equal to our require and then the FS module and down here I'm going to first of all read the file let me just do a comment so we know what we're doing send an HTML file and I'm going to say FS dots read file this is how we read files before and we pass through a relative path to the file we want to read so don't /to say the current directory then interviews then forward slash index dot HTML so that's what we want to read now we fire a callback function when we've read that and in here we pass two arguments the error if there is one and also the data from the file so inside that function if there's an error then we'll just log that to the console so console dot log and error now if there's not an error at that point we want to send this data as a response to the browser so let's say else and inside here we want to say res right and we want to pass through the data to that and then we can say res dot end to end the response and it's going to send that data then to the browser which should be the content of this index.html file now up here if there's an error then it's just going to keep the request hanging because we're not ever ending the request so we should always say res don't end here as well just end up so I'm gonna save that now and I'm going to come down here cancel out of the process in the terminal so ctrl C and then say note server once again to run it now if I go over here and refresh I should see that HTML page back which I do awesome cool now I want to show you a quick way of doing this if we're just sending one thing into response dot writes we don't actually need this line right here we can just send it directly into the end method instead if we were writing multiple things we might use response dot right one after the other but since we're only using it once we can just pass it directly into the end method instead and it still does the same thing so let me save that cancel out of this process and run it again and just demo that this still works which it does awesome so there we've got my friends that is how you send HTML pages to the browser all right there my friends so we've figured out now how to send an HTML page to the browser but at the minute no matter what URL we go to up here whether it's just the root directory or forward slash about or forward slash blogs for example we always get back the same HTML page now that's in my view would make a pretty shoddy website and you probably instead want to send back a different HTML page dependent on the routes that are use of visits so we need a way to figure out the URL that a user requests and dependent on that URL send back a different HTML file ok so the first thing I'm gonna do is create another file over here and I'm going to call this about dot HTML and I'm just gonna copy some HTML from my repo again and paste it in and this just says about at the top over here and also I'm going to create a 404 page so for a Ford to HTML and we can serve this to users that visit routes that don't exist so again I'm just gonna copy this from my git of repo and paste it all right here so this just says 404 oops that page does not exist alright so now we have those two pages now if a user goes to forward slash about I want to send back this thing right here the about page if they go to anything else other than just /or /tpour if they go to forward slash blogs that doesn't exist instead I want to send back the 404 page all right makes sense so how do we do all that well first of all let me just up here say we want to figure out the path that our use of visits so we can get that from this thing right here remember the request URL so let me say I want to create a new variable and I'm going to call this path and I'm going to set that equal to first of all dot forward slash views because remember the HTML files are inside the views folder and the path that we want to read is always going to begin with /v views and we're going to append to that dependence on the URL so we can use a switch statement to cycle through the different possible cases is it just forward slash or /y so let me do that let me say switch and then we're going to pass in the request dot URL and we're going to evaluate this value now let's add our first case is it the case that this value right here is equal to just forward slash meaning the routes of the website well if that is the case what I want to do is take the path variable and then add to it so plus equals and we want to send back the index dot HTML file so we're just adding forward slash in fact let's put the forward slash here we're just adding indexed or HTML to this path and then that's what we would go out and read okay if they just visit forward slash so then we need to say break right here to break out of the switch now the second case over here is going to be a forward slash about so if they visit that URL then I want to take the path and I want to append so plus equals and it's going to be the about dot HTML page that we send back now let me just get rid of this column we don't need the after case and then down here we can say break like so ok so if they don't visit any of these we want to send back to 404 page so we need a default case to do that so we say defaults and then down here we're going to say the path is going to be plus equal to 404 dot HTML so then we can break again like so let me just scoot this in a little bit so how is this switch working well we're setting up this path variable which starts with dot forward slash views forward slash then we're looking at the request URL so did they visit just /or /tpour or something else and we're trying to match against one of these cases if it matches this case then we're going to add this to the path then break out of the switch so it doesn't go any further down if it matches this the URL then we're going to add this to the path and if it matches none of these it will go down to the default case and it adds this to the path instead and then breaks out okay so we're using this switch statement to figure out what URL a user has visited and now we're going to take the resulting path and we're going to use it down here to read a file so instead of hard-coding this we're just gonna pass in the path like so and that's all the reason to it that's a simple routing system set up now so if I come over here in fact we need to cancel out the process and say node server again and now if I come over here and go to just the home page then we should see the home page if I go to forward slash about then we should see the about page if I go to something else entirely for example forward slash blogs we get the 404 page and it doesn't matter what that is if it doesn't exist we get that 404 page if there's not another case for it so you could add as many different routes or URLs as you want to this way Sallah my friends one part of the response we've not yet talked about is the response status code so the status code basically describes the type of response being sent to the browser and how successful the request was now there's many different status codes for loads of different scenarios but here's some common ones 200 that means that everything was okay with the request 301 means the resource was moved permanently somewhere and this is to signify a permanent redirect at 404 you've probably seen loads of times it means that the file is not found so we show probably a 404 page and 500 means some kind of internal server error now there are loads more status codes as well but typically they're all in either a 100 200 300 400 or 500 range now those in the 100 range all those codes are typically informational responses for the browser the 200 range our success codes whereby everything goes to plan 300 range codes are for redirects and 400 range codes are for user or clients errors and then 500 range codes our server errors so let's now add status codes to our responses so then to set the status code of a response is actually really really simple all we need to do is take the response object and then use a property called status code and then set it equal to something for example 200 if everything is okay now at the minute we're setting this status code right here inside the read file method now I don't want to do it here because then we're sending about the same status code for every different request because immediately after this we're ending the response so instead I might want to set a different status code dependents on the type of response for these different things up here so I'm going to set the status code in these different cases instead so let me grab that and let me paste it up here first of all so underneath the first case I'm gonna say the response status is equal to 200 because in this case they've gone to the home page and they're getting back the home page everything's okay or likewise if they go to forward slash about the status code is also 200 because everything is okay they're getting the about page but if they go to something else and try to access a different kind of page that does not exist everything is far from okay and instead I'm going to change that to 404 meaning that that resource does not exist and we're telling the browser look instead we're gonna send back this 404 page and tell you that the resource doesn't exist so I'm gonna save that and I'm gonna cancel out the process and restart the server because I've changed the code and then come over to the browser and then I'm going to inspect over here and go to the network tab now the first thing I'm gonna do is go to the home page and press Enter and we can see right here for localhost we get 200 don't worry about this five icon right now that's got nothing to do with us it's just a browser and then if we go to forward slash about we should see the same thing and we can see status 200 right there but if we go to another page that doesn't exist now we get a 404 error and we get this page instead okay that my friends so there's one more thing I want to show you in this video and that is how to do redirects so say I had a website and I had a page where I used to have the URL about - me but then later on I decided actually it should probably be just about so I changed the URL handler from about me to about and now this sends back that web page now that's fine because on my website I would probably update all of my links to be just forward slash about when they're linking to the about page now from about me but other websites might still be linking to the about me page because my websites super popular and thousands of other people are still linking to it now when they click on those links people they're gonna go to a 404 page because that no longer exists so it would be much better if I could detect requests to this URL so that then I could redirect them to forward slash about so how are we going to do that well first of all we need to add in another case into our switch statement right here and that case is going to be for about - cause so let me copy this case right here and paste it down here and take it back like so and this is now going to be not about oh sorry about me so I want to redirect this to this how do I do that well first of all I don't need to append the path because we're just going to do a redirect and I want to change the status code from 200 to be instead 301 and that means that the resource you're trying to access has been permanently moved and we're going to do a permanent redirect and that's what we're doing right the about page has been moved from about me to about by me in the past and so therefore we want to redirect them to this new URL so we've changed the status code the next thing to do is the actual redirect and we do that by using a response header so we can say responds dots it header and the header we want to set is location with a capital L and the second argument is where do we want to redirect them to well I want to redirect them to just forward slash about so that's all there is to it we do still need to end the response and we do that by saying response dot end and now if we cancel out of this process and run it again hopefully if I go to forward slash about me it will now redirect me to forward slash about so let's save that and come out here and go to forward slash about me and now it redirects us to forward slash about which is much much better so they're my friends now hopefully you can see how node works as a server and how it can handle different requests to different routes for different web pages and also how it can send back responses in the form of HTML pages now this way of working it right here using switch and finding out the request URL and all that kind of jazz that is absolutely fine but as your web sites get a little bit bigger and slightly more complex for example dealing with many different request URLs different types of requests like post or delete requests and database logic and all that kind of stuff then this way of working right here might get a little bit messy and hard to maintain now fortunately there is a third party package called Express which can help us manage all of this in a much easier and a more elegant way so I wanted to show you all of this way first using raw node and not Express because I think it's very important to understand what goes on under the hood rather than just jump right into a framework click your fingers and let it do all the magic and also this knowledge we've built up will actually make learning express a bit easier too because we kind of know what's going on under the hood so we are going to be using the Express package to handle all of our routes requests and responses later on but to do that we need to first understand how to install and use third-party packages because Express is a third party package we need to know how to use those in node and we'll talk about that in the next lesson
Info
Channel: The Net Ninja
Views: 99,482
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 request, res, req, node res req, response, request
Id: DQD00NAUPNk
Channel Id: undefined
Length: 26min 54sec (1614 seconds)
Published: Wed Jun 17 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.