Express.js Tutorial for Beginners | Learn the MVC Pattern | Build a Weather Finder App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome back to my channel in this lesson we are going to learn about the most popular node.js framework which is Express GS now Express is an awesome framework that allows you to build your node.js applications using the features such as creating routes handlers for your HTTP requests and even creating your own API endpoints so what we're going to do in this lesson is create another application that communicates with an external API and then this lays the resonator onto the screen so here if I type in Manchester press GO we can see that we get the weather information back okay so now on surface it looks like a very basic project and to be honest it is but this lesson is not so much about creating this application it's more about structuring your note applications in a way that the code we write is super organized and scalable so for this project you are expected to have a good knowledge of JavaScript and note if you are new to note then I do have a node.js for beginners video on my channel so go check that out ok so without any further ado let's jump in ok so we're gonna get started right away and get our hands dirty by writing some Express code so to do that we are going to need a folder so go ahead and create a new folder I'm going to create one on my desktop and I'm gonna call it Express - whether perfect so first things first let's launch this project into our terminal and type NPM in it ok here we go so NPM in it this command is going to open up the node.js environment for us where we can write node code and install the packages using NPM so go ahead and press ENTER a few times and once you've done that type this command with me and p.m. install Express ok this is going to ensure that we have expressed yes installed and ready to use ok so next up what I'm going to do is I'm going to open this product into my code editor there we go okay inside of it I'm going to create a new folder call its SRC and inside of this folder I'm going to create a new file and I'm gonna call it out Dodge ass inside of it just to make sure that everything is working let's just console.log hello press save and now let's head back to our terminal just to make sure that everything is working so I'm gonna clear up my terminal and type node SRC /op j/s okay so this command is going to launch this app to J's file and if you see this holo-message that means you have successfully set up your project now let's move on to the fun part where we are going to write some Express code so let's go back to our code editor and now let's first open our package JSON file and make sure that we have the Express package installs and yes we do now back in our app door J's file I'm gonna get rid of this console log and first let's import the Express package that we have just installed so I'm gonna create a new constant and I'm gonna call it Express and I'm gonna set it to require and then require the package so Express perfect so now let's first lay out a basic structure of what we're trying to achieve so here's what we want to do we want to use Express to display a web page in our web browser that reads some sort of a message so type this with me Const app equals express okay now let's create a route handler so to do that type app don't get and open up a pair of parentheses and the first argument is the route that we want to work with so inside of these coats I'm gonna pass as this as a forward slash and then in the second arguments I'm gonna pass a callback function and this callback function takes two arguments the first is rack which is short for request and the second is res which is short for response inside of this callback let's type press dot send within the coats my first express webpage okay now the last thing that we need to do in this file is create a server that can actually listen to these HTTP requests to do that just type up don't listen and then 3,000 okay so confusing stuff yet but don't worry let's break it down line by line so the first line here imports the Xpress package that we installed using NPM and the second line initializes our Express application so to initialize our Express app we have created a new constants and we have set its value to this express constant and these parentheses right next to it mean that the expressed project is now ready to use in this file okay so now this app constant whose value is set to the express function has a bunch of properties and methods that we can use in this file and one of those properties is this gap function so app load get creates a route handler to listen for the get requests that we get from a client so the first argument here in this function is the URL of the route that we want to make the get request to so in this case we are listening for get requests on our home page or simply the localhost 3,000 so there are a bunch of HTTP requests that you can use and we're going to explore a couple more in this lesson but this lesson is not about web requests so if you do want to learn more about HTTP request I will link an article in the video description okay so now the second argument is a callback function and it takes a request object and a response object the request object contains information about the request that comes back from the client which we will talk about more later on and the response object contains data that we want to send back as response to the client once they've made the request so the response object also contains a few functions and one of those functions is this red sent function that allows us to send back this string of text that we've written here now later on in this lesson we will learn how to send proper web pages instead of just this plain text but this is the meat and potatoes of setting up your own routes in Xpress so you can also create multiple routes in just one file so let's say that you have an online business and you want to set up a route handler that describes what your business is all about so to create this new handler this type app don't get and now the URL that we want to make the request to is forward slash about and then setting up a callback function and let's pass in the two arguments that we need so request and then response okay and inside of it let's send a response response dot sent and for now let's just send a string of text so we can say something like my business is so cool okay right so before we check our progress in the web browser there is one last thing that we need to cover and that is this app don't listen line so this ab dot listen function tells the server to start listening for connections on a particular ports on your computer there are a bunch of ports that you can pick from but one of the more common ports is the port 3000 so we can also give this function a callback that gives us some kind of response once the server is set up successfully so let's create an arrow function inside of here and pass this as the second argument and inside of this function less console.log something like the server is now running on port 3000 perfect so now if we head back to our terminal and type node SRC /opt ojs we can see our little message appearing here the server is now running on port 3000 but now the terminal is sort of just resting there after this message and this is because the server is now live on our localhost and it is going to stay up and running as long as we do not terminate this process in our terminal so now if we head back to our web browser and go to the localhost 3000 we can see that response that is coming back from the base URL and now if we go to the about URL we can see that response is coming back from the about URL okay so this is the ins and outs of creating a route handler in Xpress so now that we've covered that let's have a little more fun with these routes so now instead of sending back these static messages let's try to send back an actual page so by an actual page I mean a HTML template but we are not going to spend time tapping the HTML template because this lesson is not about HTML I am creating this lesson assuming that you are already familiar with the basics of web development such as HTML CSS and JavaScript so to grab the HTML structure go back to your web browser and go to this link so it's github.com forward slash Hamza Mercer forward slash Xpress - starter this link will take you to my profile on github where I've created this repository that contains the HTML structure that we need so go ahead and crack open this Xpress - tutorial folder and inside of it there are two files index dot HTML and a HTML now you can either download this entire repository or you can just crack open one of these files and then click on this Robertson right here this will give you the bare bones structure for our home page so if you press command a on Mac or ctrl a on Windows it's going to go ahead and select everything on this page and then what I'm gonna do is I'm going to copy everything go back to the vs code and then here within the root of our project I'm going to create a new folder and I'm gonna call it public inside of this folder I'm going to create a new file and I'm gonna call it index.html and paste my clipboard rights here perfect and now I'm gonna do the same with the about the HTML file so go back to the Express - starter folder and then crack open this about your HTML press Raw and then select everything copy go back to vs codes and then creates a new file and I'm gonna cool it about dot HTML and paste everything here press save okay so now let's go ahead and open one of these files so if I go back to my finder and then inside of this public folder I'm going to go ahead and launch this index.html file okay so as you can see that this is just the bare-bones plain HTML all the styling has been provided by bootstrap and it's the same in this about HTML file as well okay so now as we said we will not be covering HTML in this lesson but if you want to understand what's going on in these files just crack open one of these and have a look okay so I'm gonna close these two files we will come back to these later on and let's carry on working in our approach as file for now you all right so instead of these strings of text let's try to render these HTML templates when the user visits these URLs so now you may be tempted to do something like you know res dot sent and then go to the path of this index dot HTML file but know this is not going to work because although it is intuitive Express does not work like that expressed by default does not have access to any of your public files so there are two ways we can do this first let me show you the quote and code bad way of rendering a file so this is how you would have to display a file without using much of the functionality that Express provides so first of all I'm going to comment this block of code and now what I'm gonna do is I'm gonna say app don't get and then the URL is going to be the same as the one that we commented up there and then pass in the callback function and then give it the arguments that needs a request and response perfect inside of this function let's create another function called res dot send file ok and this function takes two arguments the first argument is the name of the file that you want to serve and the second argument is the path of the file so in this case the name of the file is index dot HTML and make sure you write this within the quotes index dot HTML remember this is the first argument and the second argument is the path so let's open up an object ok and then create a property called root and now we need to use our built-in nod module called path so first of all right here at the top let's create a new constant and call it path and then import the path module from no js' ok now something I like to do is place my native nod modules right at top of the file now you see the Xpress package is a third-party module it does not come built-in no js' so but path is actually a built-in node.js module now nine out of ten times the native modules are never going to be dependent on third-party modules it's always going to be the other way around okay now in this particular case the experts package does not rely on the path package but just to be on the safe side it is a good practice to always have your native modules before your third-party modules so what I'm gonna do is I'm going to cut this line out and paste it right here perfect okay and now that we've got this part muddled in place in here what we can say is path and then there's a method in this package called join okay and this method takes two arguments the first one is a built-in node.js puff argument called underscore underscore dur name and the second argument is a folder where our target files live so in this case the folders path is and make sure you type this within the curt's dot dot forward slash public okay that's what we need for now okay so now if you press save head back to our web browser and let me just terminate this process node SRC /op j s and now if i refresh my page we can see that we do indeed get the index dot HTML file that we put into our public folder and this is perfect now let's do the same for our about route so for now I'm going to comment out this wrapped Handler right there okay and then create a new get request so Abdo get and then set it to forward slash about and then open up the callback function and inside of it let's do request and response perfect and in here let's copy what we have in this get request and paste it right here so from this rest all the way to this closing parenthesis right here press copy and paste it there now in this case what we want to show is display the about instead of the index so I'm just going to change this to about okay perfect now if I press save go back to the terminal and let me just relaunch the process note SRC /ab dorje s and this is the home URL now if I go to the about URL press Enter we do get the about dot HTML file that we put into our public folder okay so as I said before this is not how we want to structure our app I mean imagine if you had like 60 different routes would you write this code for every single route no you wouldn't so let's get rid of these two requests okay because we're not gonna use them and uncomment out this code that we commented out first okay press save go back to the terminal relaunch the entire process and then nodes SRC forward slash app door Jess let's refresh our about and we get our original route and if we go back to our home page we get our original home page text perfect so now is a good time to use something called Express middleware now what is middleware so in short middlewares are functions that get executed during an incoming request meaning we can use these middleware functions to provide supplemental data for our requests so let's say that you are making a get request to this home URL so now during this whole process you want the request to have access to these files so in order to make the happen you can use middleware functions now let me tell ya you don't need to memorize any of these middleware functions that we are about to create because in most cases most of these just act as the Basic Express configuration and you will find them in pretty much every single note and Express project so let's get started these medieval functions are actually methods that live inside of this app object so the first one is app dot use and then it's Express dot URL encoded and then open up a pair of parentheses inside of that an object and set the extended property to false okay this function is essential for your basic project configuration the next function is app dot use and it's Express dot JSON okay this function is going to convert all parts any incoming JSON data again these are just part of the configuration and there is no need to memorize any of these okay next is app dot use and then it's Express static and this is a methods and inside of it we give passing the arguments called public okay this function is telling Express to gain access to everything that's inside of this public folder that means you do not need to declare the path to this file manually in your requests like you did previously okay and the next one is a dot set and then the first argument is views the second argument is also views now this function contains something called views we haven't talked about views yet but in essence views are the files that you render in the web browser so essentially this index dot HTML and the about door HTML are views but they cannot be considered as views why it's due to this HTML extension in the end so for them to be considered as views we need to in a view engine now there are a bunch of view engines out there the one that I like to use is called handlebars or HBS so to install it let's go back to our terminal kill the current process okay and then type and PM install HP s press ENTER ok now that it's been installed let's go back to our app to J's file and then there is one last piece of puzzle that we need to complete and that is to tell Express to use this handlebars Express engine that we have just installed ok so to do that type app dot set and then the first argument is the view engine within the codes and the second argument is the view engine that we actually want to use and that in this case is HP s perfect and with this line our configuration is now complete again if these lines don't make 100% sense to you don't worry if you continue to build more and more Express applications you will use them so often that they will become second nature ok so now that's out of the way let's move on so now let's actually try to render these pages on to the web browser using a proper way of rendering the files but to do that we need to make a couple of changes since we are using the templating engine that is handlebars we need to convert these HTML files to the files that the handlebars can read for that what we need to do is change this HTML extension to HPS so I'm gonna change this to HBS and the same with this one as well ok perfect now if we crack open one of these files we can see that the syntax highlighting is the same as you would find in a HTML file the only difference is that we can now serve these files in our JavaScript file and we can also do some cool new things that we will cover later on in this lesson okay and there is no need to import these files in our main app largest file because if you remember we did set a middleware function right there that gives Express access to the files in our public folder okay but there is one small tweak that we need to make before we do anything else so see this line of code that reads outdoor set views and then views this line is telling Express to look for these views in a specific directory which is called views we can change this to public if we want but the general convention is to create a folder called views and put your views in there so now let's go ahead and create a new folder in the root of our project and call it views okay so new folder and then views and now all we need to do is copy these two files and then paste them inside of this new views folder okay excellent so now we don't actually need them in the public folder so we can actually get rid of them so I'm going to delete the about file and I'm also going to delete the index file okay but just for the sake of this project structure I'm going to leave this public folder there as it is right so now let's actually use Express to display these files in the web browser to do that all we need to do is make changes to this res Docs and methods so Express provides us with another method called render and this render method does exactly what it says it renders a file that gets passed in as an argument so to achieve that all we need to do is convert these two methods to render okay and then instead of this static text we need to replace that with the name of the file that we want to show in the web browser okay so I'm going to change this to render and then I'm gonna get rid of this string of text and I'm gonna say that when the user visits this URL display the in file and now same thing here I'm going to change this to render get rid of the string and then we can say that when user visits this about URL show them the about page excellent press save head back to the terminal and I'm going to terminate the current process say Claire and note SRC /opt ojs and now if I visit the localhost 3000 we can see that we are actually getting this indexed out HBS when we visit the home URL and then if we go to about we do get the about HBS file in our web browser and this is perfect and in case you are wondering why we did not include the HBS extension or why we didn't include the path of the file this is because we've already told Express in these middleware functions that we are going to use a templating engine whose extension is HBS and then in this middleware function we've told Express to look inside of this views directory whenever we want to render a view okay now we can do a bunch of things in our handlebar views we can also render data that we passed inside of our get requests so check this out here inside of this get request I'm going to pass in another argument and that is going to be an object okay inside of this object let's create a new property and cool a title and I'm going to set it equal to weather finder there we go okay now because this object is part of this request that means is tied to this URL and we can actually access this object inside of the view that it's tied to in this case the view is indexed HPS so back in this index file let's find the title of this project and where is it here it is right here now to insert the title that we declared in our app door JS file all we need to do is add two pairs of curly braces so I'm going to cut this out okay and then open up two pairs of a curly braces and then close that with another pair of closing curly braces okay if you have used react this syntax may look very familiar to you so now what we need to do is throw in the name of the property that we've declared in our get request and the name of the property is title excellent now let's press save head back to the terminal and restart the process so Claire and the nerd SRC forward slash apt ojs and if i refresh the page we can see that everything is working as expected and just to prove that we are actually receiving this title from our route handler let's change this to Express weather finder okay now I'm gonna go back to my terminal kill the current process and I'm gonna restart it and if i refresh my page we can see that we get express weather finders okay and this is perfect okay so now we've covered the basics of Express and we know how to render files using a templating engine so now it's time to change our gears and do something a bit more exciting so in the next section of this lesson we are going to learn and implement the MVC pattern at this point I don't expect you to know what the MVC pattern is but just to give you a little overview MVC stands for Model View controller and following this MVC pattern is the industry standard of creating robust web applications it is one of the most desirable skills that companies look for and it allows you to keep your project super organized I am very excited to jump into it so let's keep our momentum rolling and dive right in okay welcome back so before we actually implement the MVC pattern let's make a small change to our project because this section is all about keeping your project organized and for that reason we're going to make some changes to our app dot J's file okay so we want our app dot J's file to just act as an entry point that means we don't want anything other than our basic configuration and the call to the server in here and not even these route handlers so to do that let's create a new file inside of this source folder that's going to be responsible for handling the routes so here let's create a new file and call a router GS excellent inside of this file let's first import Express so Const Express and set it to equal require and then Express perfect now check this out Express gives us access to its own built-in router and its job is to handle the routes nothing more nothing less so to make use of this router let's create a new constants call it router ok and set it to equal Express dots router and then a pair of parentheses because it is a methods so you can think of this router as the mini app now we can use this router constant to set up our routes much like we did in our app your J's file so what I'm gonna do is I'm going to cut all these routes and then paste them in my router J's file so I'm going to cut this to my clipboard okay go back to the router J's file and now I'm going to paste them here so what we need to do now is replace this app with the router that we've just created up there ok so there we go excellent and then since we are using our app your J's file as the entry point we need to import this router in our a pledge as well and for that let's say module don't export and set it to equal this router constant up there okay press save now let's head back to our app the J's file and here we need to import the router file that we've just created so cons router and set it to equal require and then a stop forward slash router excellent and now to make use of it all we need to do is write here say app don't use and then we're gonna use the base URL which is the forward slash and the second argument is going to be the router constant that we just created up there okay this line is going to ensure that all the routes get handled but Express router but they end up here in this applet just file because this is where our server lives right there so now to test our progress in the web browser I'm going to go back to my terminal and I'm going to launch this file and then here let's press ENTER and see what we get back so we can see that everything is working just as expected and this is perfect now let's talk about the V in MVC we already known that the V stands for view and now view is all the codes that we display in the web browser so that means that these two files the index dot H PS and the about dot H PS are actually views so if you look at it this way we've already been working with the V in MVC since we introduced our views we just didn't know that now that it's other way let's talk about the C in MVC which is controller a controller is where we put all our logic and it is also responsible for interacting with the views so if you think about it what file in our current project is interacting with the views it's this router J's file isn't it because that is where we are handling all of our routes now the issue here is that the router file should handle the routes and routes only that means whenever we visit a given URL is the job of the router file to tell the web browser to launch those routes but what we are doing here is in this file we are declaring the routes which is fine but we're also interacting with the views and that's not right because that's the job of the controller but the question is how do we figure out what's a controller and how do we make it interact with our views well let's create a new folder inside of our source folder and call it controllers excellent now inside of this folder let's create a new file and call it controller is perfect now this is where we are going to put all our logic that's going to power our web app so the first thing is let's use this controller to interact with our views and doing that is as simple as creating a new route handler just like we did in our app door GS and router GS files however structuring this file is not very simple because you see we want to create some functions here that are going to handle the routes so instead of getting into creating separate functions exporting them them individually and then risking messing up our code we can just create named exports that we can then use in our router file so check this out we can start with the keyword exports okay this is going to make sure that the function is ready to be exported right from the get-go so exports and let's call this function render home page and then set it to equal an arrow function and then inside of it let's pass in come on can I just type in an error function please yeah there we go and inside of it let's pass our request and response arguments now inside of this function we can just say R as don't render and then we want to render the index view okay now let's go ahead and do the same for the about route so I'm actually going to copy this and paste it here and I'm going to change this to about and I'm going to change the name of the view to about as well okay press save now back in our router file we need to import this file that we've just created so right here at the top let's say Const and call it controller okay and then set it to equal require and then we need to jump up one directory no it's actually within the same folder so we need to go to controllers and then select this controller file now I'm going to select everything from the start of this callback function all the way before the closing parenthesis of this get request and I'm going to delete it so from there all the way till there and now we can access the render home page method that lives in this controller file that we have just exported so we can say controller dot and then we can see that in the suggestions we've got the render home page there already okay now let's go ahead and do the same with our about route so I'm going to get rid of my callback function and I'm gonna say controller dot render about page X events press save and now there's one more thing we need to do so back in this index dot HBS file we need to get rid of this this little constant because there is no title in our object anymore so if we just go back to our router I'm sorry controller you can see that there's literally just this index page we're not actually creating a new object and declaring the title property so let's just replace that with weather finder okay we will make further use of these objects that we can declare inside of our routes but there was no point in just rendering out some static text so now let's head back to the terminal and then we start this process so note as RC apt rjs and now if I visit this URL again we can see the change that we just made and then we can visit about URL as well and we can see that we're also getting the the contents of the about page perfect now I realize that this part might be a bit frustrating for you you might be thinking why do we need to create all these separate files and split up a code like this but trust me when I say this implementing these industry standard practices it's what's going to set you apart from other developers I know this is not a very comfortable approach but trust me you never grow in your comfort zone you know stepping out of your comfort zone is the best way to grow as a developer or in any other aspect of your life so if you were able to follow along congratulations you now have taken your skills one step further okay so we've covered a lot of ground in this section so let's review what we have done so far so first up in our app DOJ's file we are kick-starting everything by setting up some basic configuration again if these lines are confusing don't worry we will cover these as we continue to use them after that we have imported the router DOJ's file right here and then right at the end we have the call to our local server now inside of our akhada JS file we have set up the routes using something called Express router this Express router is the same as the App object that we have here in our app door JS file except the only job of the router is to create routes nothing else now these routes are actually being managed by our controller so in this controller dot JS file we have the named exports which are functions and these functions are essentially the callback function that actually take place in our route handlers the only reason we have a separate file for managing these routes is because these routes are part of setting up our logic a bit later in this lesson we will be making API calls handling errors and darts and we don't want to clutter our router to J's file with all that logic handling the routes is the responsibility of the controller and it also interacts with the views and here you can see we are entering the views that live inside of our views folder so we have covered the V and the C in the MVC pattern so far what's left now is the M which is the model we will cover that later when we actually start creating our weather app and guess what that is actually what we're going to do in the next section so hang tight and I'll see you then all right so now that we've covered the basics of Express and we have a good understanding of how it works with the routes and the views to actually build a web page let's go ahead and create a project to solidify our understanding so we have everything in order to get started we have the views that contain the templates that we are going to render and we have a good project structure in place so let's jump in so obviously with the weather app we are going to need a forum and an input fields to enter the name of the city and that form lives inside of our index dot HBS file so crack up on that one and scroll down to the forum and in this forum let's give it an action and that is a built in HTML attribute and set it to equal /or the base URL and let's also give it a method okay and set it to equal post perfect these attributes are going to allow us to send off of a request to the weather api service whenever we press this go button right there next let's give this input fields a new attribute called name and set it to equal city so name and then city this will allow us to read the value of whatever the user types in this input fields okay and here I don't even know why I typed - 0 degrees there is no such thing as the negative zero I would make a table by the man anyway let's continue right so now let's actually try and see if this form works to do that we need to make a new type of request to our base URL and this type of request is called a post request we make a post request when we are sending of the data to the server so in a get request what we do is we are requesting the data we enter the URL and then we wait for the server to send us the data back in a post request however we send the server our own data to work with so for example whenever you sign up or login to a website you are making a post request and that request sends your credentials that you type in to the web server and then that web server interacts with the database and see if your credentials match the ones that live in the database so let's crack open of a router GS file because that is where we are handling the routes this time we're gonna create a new route but this one's gonna be a post request okay so just below this router don't get requests we're gonna say router dot post and then the URL that we need to make the post request to is this base URL so just the forward slash and if our form and input lived somewhere else for example if they lived in this about the HBS file then we would have to make the post request to this forward slash about routes okay so now that we have our route in place let's place our callback function and call it controller dot get weather excellent now to actually create this function we need to open up our controller ok and just below this render home function let's create a new named export and call a exports dot get weather and then set it to equal an error function and then inside of it first of all let's place in our arguments a request and response now right here for the time being let's just say res sent and then a string of text that reads your form has been submitted excellent now let's press save and then go back to the terminal and fire off our app dot JS file so note as our see /ab Dorje s and now let's go to our localhost ok and now let's go ahead and press this button and see what happens so when we press this we get the message that reads your form has been submitted perfect so next up we need to see if you are actually able to access whatever the user types in this input fields is this input right there so in this case it's going to be the name of the city so we need to see if we have set this up correctly now the question is where does this value get stored I mean we know that in a regular JavaScript file we can access the value of the input using the name value property but in this case we are working with Express so Xpress stores all of the data that we sent in this other argument that we haven't talked about yet and it's these request arguments this request argument is actually an object so let's console.log this request property as soon as we make the post request so right here just say console.log and then request press save now let's head back to the terminal okay terminate the current process and say note as our c /a blah yes now let me refresh this page and here i'm gonna type in manchester okay and now if i press GO and if you look back into the terminal we can see that there's quite a bit of data okay but let me tell you 99.9% of this is irrelevant to us in this case the only property that we are concerned with is this body property right there as you can see that this body has an object this one right there and inside of it we have a property named city which is actually the HTML name attribute that we gave to our input in the index dot HBS file and then it's value is Manchester so now to actually use this inside of our project let's go back to our controller okay and here let's get rid of this string once and for all now let's open up a pair of Baptists to initiate a template literal and here let's type you typed and then a dollar sign followed by a pair of curly braces now to access the value we can say request dot body and then inside of that the name of property that we want to access is City okay and then a full stop here and let's get rid of this console perfect so now let's go back to the terminal again kill the current process and then refresh the page right so now let's type in Manchester again press Co and let's take a look in the terminal and there is well look not in the terminal actually we get the message that says you typed Manchester and then if you type in something else let's say we say Leeds press Co we say you typed Leeds so everything is working as expected all right so now that we've got everything in place we have all the routes set up and we're able to access the input data let's actually go ahead and use the weather API service to effect some weather now if you have watched any of my previous videos you know that I absolutely love the open weather map in my opinion is just super easy to work with and it's amazing for side projects as well as tutorials so it is go to this link open weather map the org forward slash API and if it asks you to sign up or sign in you have to do that in order to obtain the API key so go ahead and click on this sign in Watson and in my case I am already signed in but once you've done that then press this API key section and this is where you can obtain the API key that you need now let's go back to vs code and right here at the top let's create a new constant in all capitals called API underscore key and set it to equal a new string and inside of it let's paste our API key excellent now let's go back to the web browser and go to this API section right here at the top now from here we want to access the current weather data and it's actually the first one right here so let's click on this API talk button now we need to find the link that we want to make the request to okay and the link is this first orange line that we see right there so let's go ahead and click it and here is all the data that we need right so before we continue Natalia that this lesson assumes you already know how to work with api's I will explain what we're doing as we go along but if you are new to AP is that you might want to check out a beginner friendly API tutorial I do have a couple of those on my channel in plain JavaScript as well as in react and notes that go check them out okay so the property that we are interested in is this main property right there because that is where the temperature property lives and then to access it we'll have to type something like main temp but first of all we need to find a way to make the API call and the way is actually pretty simple we are going to use a third-party library called Axios to make the request so let's open up our terminal kill the current process and type and PM I X years press Enter excellent once it's been installed let's head back to our package.json file just to make sure that it is actually there there we go so first things first let's import this library in our controller so back in our controller dot JS file before our API key constants let's create a new constant called X years and then require the package that we purchased installs and Axios perfect now here in this get by the function let's first get rid of this line because we don't need that and now let's store the value of the city into a new constant so let's say Const city and then set it to equal request body dot city now remember this line means that we are accessing the property does the city property from the body object that lives inside of this request argument right there okay now press save and then go back to our web browser and now we need to copy the URL that we want to make the API requested and it's this URL right there so let's go ahead and copy it now let's go back to vs codes and create a new constant right there okay so Const and let's call it URL and then open up a template string now the reason we're using a template string and not a regular string is because we are going to append this API key constant right at the end of the URL so let's open up a template string okay and paste the URL there now to actually append this API key we need to say the end % right at the end of this URL and then type a double PID and set it to equal a new object literal just like that and in here we can append the API key constant that we've declared up there okay now press save so now we are in a pretty good shape to actually make the API call and for that we need to use the xes library that we have just installed so let's go ahead and use a method that comes with X years and is calls get so the get method takes in the one and only argument and it's the URL that we want to make the request to so inside of our get weather function let's say X years don't get and then the URL that we need to make the request to is the constant of there perfect now since X is a promise based library we need to resolve the promise and then catch any errors that may occur during the process so right after this get method let's create another method or append another method called then and then another methods called cat so after that let's append a new method called cats and close it with a pair of parentheses so the then method takes one argument it's actually a callback function and then this callback function takes one argument itself and this argument is going to store all the data that we get back from the API as an object so you can call it whatever you like I'm just I'm going to call it response and for now let's just go ahead and console.log this response argument okay now we still need to work with this catch phrase so this also takes one callback function and then this callback function takes an argument called error and for now let's just go ahead and console.log this error okay press save and now it's time to test things out so let's go back to the terminal okay and relaunched our app that J's file so notes SRC /opt ojs now let's head back to our localhost okay and type in Manchester now as soon as we press GO we should get the results from the API and they should look pretty similar to what we have over here so let's see if we can actually make this work so press GO and what we have here is not very promising you see it's it's some sort of a warning it's not exactly an error but it's also not giving us the results that we're looking for I mean all we should get back is this whole object right there but what we have here looks nothing like what we want it to look like so what's going on so the reason we're not getting the results we want has nothing to do with our code and it's everything to do with this URL right there you see it just starts with this API dot open weather now there is nothing wrong with that but I mean it's a perfectly secure website but Express and xeo don't know that Axios and express want to make sure that we are not making any web requests to any unsecure websites and that is why we're now getting the results that we want so to fix this we just need to make a small change to this URL all we need to do is prefix this URL with HTTP colon forward slash forward slash this prefix is going to assure Express and X use that this is indeed a safe and secure URL so now if we head back to the terminal ok and then restart the current process now let's go back to our web browser and then pressing this go button is going to fire off the Axios get requests so let's press it now head back to our terminal and it says the reports is not defined and why is that actually it this should be response sorry my mistake now let's head back to the terminal and then restart the current process and then go back to our web browser press GO now we should have the data that we need and it is definitely there so this is the whole object that we're going to be working with so it lives inside of this data object and then inside of this data object at this main object and then it should be it's gonna be something like data main temp and this is perfect now I don't like that these these you know temperatures these values are being displayed in a Imperial format I mean I'm British I live in England I'm used to seeing the metric format okay so to fix that we can go back to the code editor and we can make a change to this URL again now open where the map gives us the app that gives us the option to change the unit so if we scroll right at the bottom we can see that we do have an option right here and here what we need to do is right at the end of the URL we need to say units and set it equal to metric okay so now if we head back to the code editor and right at the end of our URL after this API key constant let's say another + % and say units and set it to equal metric press save now obviously if you live in the US or if you are somebody who is used to seeing the imperial system feel free to leave it leave it as it is but I'm more comfortable with the metric system so this is why I've done that's okay so now let's head back to the terminal just to make sure that everything is still working and I'm going to terminate the current process and I'm gonna say know it as RC approach yes now let's go ahead and relaunch our localhost press GO and now we can see that temperature is being shown in this metric format and this is perfect now keep in mind that this is the temperature for London and the reason for that is because we are making the ape we're making the call to the URL that has London right here now to fix this we will have to replace this London City with our city constant that we declared right there so to change that let's actually cut this URL okay and paste it right here inside of our get weather function now to replace this London with our city we already have a template string so I'm going to get rid of this okay and I'm going to say dollar sign curly braces and then replace this with the city now whatever we type in our input field is going to act as a placeholder right here so let's go back to our terminal again restart the process and then go back to the web browser and say Manchester and press GO and now we can see that the temperature is different twelve point one four but most importantly the name of the city now is Manchester and we can prove it that is actually working by let's let let's replace this with Leeds press GO and now we get in the weather for Leeds so it's seven point zero five and the name of the city is Leeds so everything is working just as expected thankfully okay so now let's extract the properties that we need from the API so let's open up a terminal and see what we need so I want to display a message that reads something like it's currently X degrees in X City so for that what we need from this API response is this temp property that lives inside of this main object and then this name property that lives right there so let's go back to vs code and then inside of this get ready function let's console.log our template shrink and then inside of it let's say so I'm gonna get rid of this response so open up a pair of backticks and then let's type it is currently and then to access the temperature property we can first open a template literal so a dollar sign followed by a pair of curly braces and then it's response dot and remember this is where all the data is stored and then we need to access the data objects our response data and then its main and inside of the main object we have a temperature property so response data main temp and then we can say that so so far it reads it is currently X degrees well whatever temperature we get back in and then we need to type in the name of the city so dollar sign a pair of curly braces so then we can say response dot data and then its name and then a full-stop perfect now let's test our work in the web browser well in the terminal because this is very log in our data so let's go back to the terminal and then kill the current process and then it's no it's SRC I pledge yes now let's refresh in the web browser and now here let's say some let's say Paris okay so now if you press GO we should tap our message and it reads it is currently six point eight nine in Paris so this is absolutely amazing because what we have done now is we have interacted our front end with our back end so our front and being this view and now we are using our front end to interact with the back end so our back end being this console.log right there so it is working as expected so far let's carry on okay so now let's go ahead and try to display this message in our views so I'm going to kill this process in the web browser and now what we need to do is back in our beer skirt we need to cut this line outs because we will need it and just to live it okay and now let's use the rest render method to display the webpage so I'm going to get rid of this console log and now say res render and then let's render the index dot HPS page because this post request is taking place on our base URL okay so now the question is how do we display that message on the screen so if you remember in the beginning of this lesson when we were learning about Express and templating engines we learned that we can create our own objects inside of the route handlers so let's pass in an other argument right next to this index view okay and that's going to be an object inside of this object list creates a new property called weather and then we're going to set its value to the line that we just got up there okay perfect now to display this message in our view let's crack open our index tour HBS file and this is where we want to display the message so currently it's just the static text and let's get rid of that and now I'm going to open up two pairs of curly braces okay inside of it we can throw in them the the weather property that we just declared just like that now remember this will only show up once we have pressed the Go button because by default we are rendering this view in a get request but this weather property is now part of the post request okay so let's save this file head back to the terminal and I'm going to relaunch this process note SRC approach yes let's refresh in the web browser and type Paris let's see what happens and we get the message that reads it is currently six point seven one in Peretz let's try Manchester and we get it's currently ten point oh five in Manchester which is a bit unusual because at this time the gear is absolutely freezing okay so we now have a semi complete version of our app we still have a long way to go before we actually complete this project so let's keep our momentum rolling and I'll see you in the next section okay okay so in this section we are going to try and understand the M in MVC which is the model so let's just do a quick review of MVC so far we've covered C and V so as we know V is the views so this folder right there and the views are fairly straight forwards so views are what we display in the web browser after that we covered C which is the controller okay so a controller's responsibility is to contain all the logic of our project and it's also responsible for interacting with the views as well as the model so you can say that the controller is like the middleman now finally what is a model so a model is responsible for containing all the rules and regulations that we want our application to follow for example we want to set a rule to this input in the web browser okay this one right there so we want to set a rule to this input that and the rule is that it cannot be empty so if the user tries to submit an empty input we cannot let them do that all right so hopefully you are starting to see the bigger picture here the M is the model where we can set all the rules and essentially model our application data the V is the view that we display in the web browser and finally the C is the controller where we put all our logic and it's also where we interact with our views as well as our data model and all of this comes together in the end to make the MVC pattern okay so all this sounds good in theory but let's actually put it to practice so let's get started by creating a new folder inside of our source folder okay and call it model excellent and inside of it let's create a new file called whether Jas and whether with a capital W it doesn't make a difference whether the first letter is upper or lowercase is just a convention to name your model with a capital letter okay so now inside of this model let's create a blueprint or a constructor function called feather okay so let's say Const weather and then let's create a new function okay perfect now here let's give it a new property by saying this data and set it equal to data and now let's set a new argument here called data okay because that is what is the data is going to be pointing to it so this data right there is this placeholder right there in the argument and I will come back to what this data actually means just in a little bit first of all let's fill out our weather model okay now let's create a function that's going to check if the input is empty or not and we could call the function something like validate user input and then set it up inside of this blueprint function there is absolutely nothing wrong with that but let me show you a cleaner way and a more scalable way to setting up new methods so we can use Java scripts prototypes to create new methods okay so check this out we can say whether dot the keyword prototype and then the name of the method we want to create so in this case is called validate let's call it user input and then set it equal to a new function excellent in here let's say that if the data so if this dot data is equal to an empty string than what how do we display an error message so there are a thousand ways you can accomplish this but here is how I'm going to do it so in sight of our main blueprint function I'm going to create a new property called this dot errors and for now I'm just going to set its equal to an empty array okay now back in this prototype function let's create an if statement okay and then in here let's say that if this dot data is equal to an empty string then we want to push a string inside of our errors array so let's say this dot errors if I can spell errors that'd be brilliant okay this dot orig push and remember push is an array method in JavaScript and here let's create a new string and say please enter the name of the city excellent now one last thing we want to do is make this file available to our controller so right here in the end let me just format that so there we go okay so right here let's say module dot exports and then set it equal to our weather model okay perfect so one thing that we haven't talked about yet is this this dot data property I mean what is this what is going to be as value so check this out let's go back to our controller and in here let's create a new constants called weather and remember is the weather with a capital W okay so con Strether and then first of all let's require in our weather models so I think the path is dr. forward slash and then model and then weather perfect and now inside of this get by the function let's create a new variable okay well a new constant so let's call it weather so Const and this is going to be a lowercase W weather so conce together okay and then set it equal to an instance of our body model so to do that we need to say new weather okay and since it's a function it takes one argument so if we go back to the weather JS file we can see that it takes one argument which is data now obviously if we are initiating this function here we need to pass in an argument now what could the argument be well it's going to be the name of the city that the user is going to type in so in other words is going to be the input value and remember the value of the input is request dot body dot city excellent after that let's call in our data validation method the one that we made here okay so weather dot prototype is validate user input so let's go ahead and copy it and right here let's say weather dot and then it's the validate user input and let's call in this method okay now let's create a new if statement and check for any errors so to begin with our errors array this one right there it's empty meaning there are no errors however if there are any errors then the length of the array will be greater than zero right so let's say that if this so in here come on let's create a new if statement okay and say if weather dot errors dot length okay now this is checking that if this evaluates to true so true is obviously not zero in JavaScript or any programming language so zero is is a faulty value and anything greater than zero is a truth eval you so if the length of the weather if this errors array is greater than zero then this condition is going to be true so in this case what we're doing is we're checking that if the weather if the length of the errors array is greater than zero then what we want to do is we still want to render our indexed or HBS page so R as the render and in here let's say index but then we also want to create a new object and give it a property called error ok now inside of this error property we are going to set it to equal weather dot errors and now to actually put the error out we can use a built in javascript methods called two string perfect now after this if block let's create an else block so after this curly brace let's say else and then cut our X's get requests so from there excuse the word Axios all the way to this closing parenthesis okay let's cut this out and then paste it right here perfect so this code will only run if the first condition is not true meaning we are not going to make an API call unless there are no errors in our errors array okay now one last thing we need to do is render this error property in our index dot HBS file so let's open up our view and below this weather lets open up two new pairs of curly braces and in here we can type error excellent okay so now it's time to test things out so let's go back to the terminal terminate the current process and then restart it now refresh in the browser first of all let's try to get the weather for a new city let's say Prague okay press GO and we are getting the Prague error I'm sorry the prague better which is minus one point four six now let's see what happens when we press ko without typing anything in this input fields press GO and we get the error please enter the name of the city this is perfect right so our application is now complete for the most part now let's make a few changes to make it better first of all let's go ahead and try to make these two buttons work I feel bad for them because we've been working on this application for over an hour and we didn't even talk about those buttons I feel really bad for them let's just take a moment of silence okay so now let's give them a bit of attention so let's head back to our code editor and in here let's open up our views and in my case I already have my index dot HBS file open so what I'm gonna do is I'm going to find the nav bar because that is where those buttons live and here in this anchor tag the first one is the home so here to direct it to home all we need to do is pass in the href or forward slash because that is the base URL and now we have another button and anchor tag for the about button so we need to in inside of this href we need to say full slash about I need to breathe okay so now let's go ahead and do the same for the about door hp's page so here let's give this the href or forward slash and this the hate ref of forward slash about excellent so another thing that we can do to make our code a bit more scalable is go to our controller ok and then we can use the JavaScript object destructuring method to extract out these temperature and the city properties so inside of this ex yours request let's create a new constants okay and now to use that destructuring we use the curly braces and now what exactly do we want to extract so we want to extract this temp property out of this response data domain and then this name property out of this response to data so within this curly braces let's say temp and set it to equal response data domain okay we can even go one step further and give this temp property our own preferred name so to set a new name we use a colon just like that and I'm going to call it temperature okay that's not right temp ratchet okay now let's go ahead and copy this slide paste it below and here we need to do the same for this this the name of the city so here the name of the property is city but sorry the name but the my preferred name is location okay and now here we can get rid of this domain because we're just extracting out this property from response data okay so now we can use our own preferred names instead of these properties that we have there okay so let's go ahead and copy this temperature property and paste it in place of that and let's copy the location and paste it in place of that and look how much more cleaner this is this is a lot more nice to look at okay so now press save and it's time to test things out in the web browser so let's go to the terminal and kill the current process restart it refresh in the web browser and first of all let's try to get the weather over city so let's say we want to get the weather for Manchester so there's the weather for Manchester which is very cold at the moment and let's try to submit this form without typing any values so press GO and we get the error message perfect and let's not forget about these two buttons up there so let's press about and we get taken to the about page and now if I press home we get taken back to the home page excellent okay so now with everything in place our project is complete we have covered a lot of ground in a very short span of time we've learned about express handlebars routing HTTP requests API and the MVC pattern so I hope you found this tutorial helpful and if you did please show me some love by dropping me a like and I shall see you next time goodbye
Info
Channel: HamScript
Views: 23,810
Rating: undefined out of 5
Keywords: JavaScript, JS, js, express.js, express, node, Node.js, MongoDB, express for beginners, node.js for beginners, html, css, Node.js project, API, Node.js APIs, Weather App, Weather Finder API, MVC, learn MVC, MVC tutorial, MVC in Node.js, Express.js API MVC
Id: dDjzTDN3cy8
Channel Id: undefined
Length: 82min 50sec (4970 seconds)
Published: Thu Dec 12 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.