Express JS Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] this video is sponsored by the ultimate freelancing bundle by study web development comm which gives you everything you need to start your own freelancing business including 130 page in-depth guide invoicing and client proposal templates website templates an SEO checklist and much more visit the link in the description and use the code brad 25 to get 25% off hey what's going on guys welcome to my Express crash course so a couple weeks ago I did a 90 minute crash course on nodejs and this is the next step seeing that Express is the most popular web framework for node and even if you've worked with Express before I'd still encourage you to watch because you'll most likely learn something new somewhere along the way so we're gonna quickly look at some slides and then we'll jump in and we'll start to look at how Express works so let's first talk about what Express is it's a very fast uh opinionated and minimalist web framework okay so we all know what fast means it's it's it's very high-performance unup enya nated basically means that it's it's not a high level framework such as laravel for PHP or Django for Python it's very basic at its core and it doesn't assume that you're gonna build your app or API in any certain way with any certain design pattern you have absolute full control of how you handle your requests to the server and how you respond and that's also what makes it minimalist now I'm sure most of you know this but Express is a server-side or a back-end framework so it's not comparable to client-side frameworks like react or angular or view in fact it's it's often used in combination with these frameworks to build very powerful full stack web apps many times you'll build out the API with Express so that it takes requests from the front end and then it serves back data usually in JSON format and then you can do what you want with it in the front end to render your your basically your client side views now you can also render views with express using either just plain HTML or you can use a template engine like handlebars or pug so there's a lot of different options when it comes to building web apps using Express so let's look at why we would use Express well for one thing it makes building node web apps about a hundred times easier if you watch my node crash course and you built out the simple web server there was quite a bit of code there to do to do something very very simple we had to manually grab the URL load the file check the content type it was very tedious Express makes handling requests very simple and it's much much less code so like I said Express is used for both api's that serve JSON data as well as back-end applications that render pages on the server okay it's exciting like I said it's extremely fast it gives you a ton of freedom it's by far the most popular framework some other examples of node frameworks are koa happy Jas and Adonis which are all great but they're nowhere near as popular as Express koa and happy Jas are very similar to Express however Adonis is much higher level in my opinion Adonis is very similar to laravel for PHP and it gives you a lot more but you also don't have as much freedom and it's a much larger framework so the next advantage is is true for just node itself and that's that it's it's JavaScript so if you're building a full stack app with like react you could you're still using JavaScript on the server side so there's no need for multiple languages so that's always an advantage but that's not just for Express that's any anything that has to do with node so as far as what you should know before starting to learn Express I would say at the very least you should just be comfortable with JavaScript I'd also suggest having at least some basic knowledge of node as well as NPM which is the node package manager I'm not saying you have to be a nodejs pro but at least watch you know a couple tutorials so you understand what it is maybe look at some of the core modules that are included and so on alright so some other things that can help you out is knowing about HTTP knowing the status codes you're dealing with requests you're gonna have to send back responses so it's helpful to know which which type of response you should send back Jason if you're dealing with you know building api's high-order array methods arrow functions promises all the newer features of JavaScript they're commonly used with known as well so I would suggest getting familiar with that stuff all right so let's quickly look at just the basic syntax of a web server so this is the absolute bare bones to get a server to run in the browser so basically we just bring in Express at the top using the the common j/s module syntax note you can't use the import the es2015 modules with node by default just yet if you do want to use it you'll have to use something like babel to compile it how otherwise you're going to use this syntax and then to initialize Express you just set a variable to the express method here usually called app and then you create your endpoints so in this case we're accepting a get request to the index route which is the slash and then we just have a callback function that takes in a request and a response which we'll talk a little bit about in a second and then we just do whatever we want in this case we're just responding with the text of hello world and of course we need to listen on a port so in this case we're listening on port 5,000 so if we went to localhost port 5000 in our browser we would see hello world okay and of course you can create routes to whatever you want if you wanted to do slash users or whatever and you can also include parameters and we're going to get into all that stuff so within your route you can do just about anything fetch data from a database you can use MongoDB is very popular to use with node but you can also use postgrads MySQL there's third-party packages for just about any database okay you can load pages you can return JSON data you have full access to the request and response now the request and response objects are very important the request object represents the HTTP request properties for things like URL parameters query strings any data that's sent within the body the HTTP headers all this stuff is included in the request you can also create something called middleware which I'll talk about in the next slide where you can change or add things to this object and then the response object represents the HTTP response and in it's up to you to use this object to basically send back you know JSON data do you want to render a template so you can do multiple things with this response object if you want to redirect you can do rezident redirect so we're gonna look at more in-depth into both of these objects as the course goes on and then we can parse any incoming data with the body parser that's included with express also we don't have to put all of our routes in one file Express has a router so that we can store routes in separate files and then we can just exported alright so the last thing I want to talk about real quick is middleware this is something that seems to confuse a lot of people middleware functions are they're just functions that have access to the request and response objects okay just like we do within routes Express has its own middleware and so do you know third-party packages that you install we can also write our own middleware functions which I'll show you how to do middleware is is capable of executing any code making changes to the request and response objects editing the I'm sorry not editing ending the response cycle also you have to call the next middleware in the stack so when you write a piece of middleware you'll call a next function so you can just think of it as kind of a stack of functions that executes whenever a request is made to the server and you can do different things within those functions that's the gist of it alright so enough talk let's jump in it's much easier to see examples rather than me try to explain it so we're gonna jump in we're gonna look at pretty much all the fundamentals of the Express framework alright guys couple things before we get started obviously you're gonna have to have no js' and installed on your system if you don't just go to node.js org and go ahead and download and install it now this is the Express website Express j/s comm which has pretty good documentation has guides we are using version 4.16 point four in this crash course however version five is in alpha at the moment if version five is stable by the time you watch this you should still be alright because most of the syntax everything that's on the surface is pretty much the same so you should be alright even if even if version 5 is an elf I'm sorry is stable so I'm gonna be using postman which is an HTTP client to make requests to our server okay so postman can make get put post delete requests so I'll be using that so if you're going to follow along I would suggest downloading that as well from from get postman com ok so I'm gonna jump into vs code which is the text editor I'm using of course you can use any text editor you want I'll be using the integrated terminal as well as far as you know installing packages and stuff like that so I just have an empty folder called Express Express crash course and first thing we're gonna do is create a package dot Jason so I'm gonna do NPM an it and I'm just gonna add on the dash Y flag so that I don't have to answer any questions ok and that you can see that that creates a package.json file now we're gonna want to install Express there's a couple things that I'm going to install throughout this course but right now I'm just going to install Express so I'm gonna say npm install or i express okay so that gets added to our package jason and now i'm gonna create our main entry point file which i'm gonna call index dot JSP really doesn't matter what you call it so here we're just gonna start off by creating just a simple Express server and just make this a little smaller alright so we're gonna first bring in Express so we're gonna create a variable and we're gonna set it to require Express all right and then what we want to do is initialize a variable called app with express all right now this app has a bunch of properties and methods one of which is listen so that's what we need to use to actually run the webserver we want to listen on a port okay now what I usually do is create a variable sometimes in a separate config file but I'm just going to create it here and we want to set this to a port number so I want to use 5,000 in development however we want to also add here process dot env which means that we want to look at the environment variables we want to look for one called port okay and then we just want to put or so double pipe character is going to be or now the reason we put this is because when we deploy the server isn't most likely isn't going to run it on 5000 it's going to have the port number in an environment variable so we want to check that first okay if that's not available then we want to run on 5,000 okay so then down here and listen we just want to put in our port variable and we can also add a callback as a second parameter and I just want to do a console log because when we run our server I want it to let us know in the console that it's running so I'm gonna put in some back ticks and I'm gonna say server started on port and then we'll go ahead and put in our port variable okay so just doing this will actually run a server so I'm gonna save it and I'll go down here and I'll type in node and then the name of the file which is index and you can see server started on port 5,000 all right now if I go to 5,000 so localhost and we want to go to colon 5,000 we're gonna get this message here cannot get slash so slash is the route for the index page and it's basically just saying that it can't find a route handler for this slash okay if we try to go to like slash a boat it'll say cannot get slash above because we haven't created any routes any endpoints so let's go back in and let's create a route here so to create a route we want to use App and then the type of requests that we want to handle now when you just go to a web page that's a get request so we want to do app get and then the road is gonna be just slash and then the second parameter is gonna be a function okay if you want to use this syntax you can do that and pass in your request and response however I'm going to use an arrow function so I'm going to get rid of the function keyword and just gonna put an arrow here alright now the every route we create is gonna we're gonna have access to this request and response object we're gonna look into both of these as as we move along here right now what I want to do is just take the res the response object and it has a method called sin that will just send something to the browser so some text or whatever so I'm just gonna say hello world okay we could actually put HTML in here so if I wanted to put an h1 we could do that and we'll save it now if I go back and I reload notice that it's not working and the reason for that is by default we have to restart our servers down here we'll do control C and then run node index again and then if we go back we'll get hello world now it's just the h1 if we look at the source code oops don't open that let's look at the source here and you can see it's just an h1 there's no doctype nothing like that there's no content type so this is obviously this isn't what we want to do I'm just showing you this as an example so let's head back in and I don't want to have to keep resetting the server every time we make a change so what I'm gonna do is install a package called node Mon which will constantly watch our server so we don't have to keep reloading so I'll ctrl C to stop and let's do NPM install and I'm gonna add dash D because I want to install this as a dev dependency and then node Mon okay it's a dev dependency because it's only for development we're not using it in production all right so now we have node LAN installed now to use it we're going to go into our package Jason and we need to create a script okay so we're gonna actually create two script one is gonna be--start which is just simply going to run node index so that will most likely be used in deployment and then for dev I'm going to create a script called dev and we're gonna use node Mon index okay and the difference is node index you'll have to keep resetting the server every time you make a change no lon will constantly watch it so we'll save this and then let's go down here and run npm run dev okay so you can see it's running on 5,000 however node maman is running so if I were to go here and let's say add some exclamation marks and save and go back and reload you can see that the changes are made I don't have to reset the server okay so node Mon is an extremely handy tool now as far as what we send as a response we have a bunch of different options obviously we have send but we're not going that's not used too much we could send a file a single file if we want I'll show you how to do that we could send Jason with res dot JSON we could do res dot render if we had a template engine we could actually render an HTML template where we could actually put variables in and stuff like that some examples of templates are pug which I really don't like I don't like the syntax I usually use handlebars or ejs if I'm rendering templates on the server now what I want to do is bring in the path module which is just a node.js module to deal with file paths and I'm gonna just load an HTML file here so I'm gonna say instead of res send I'm gonna use send file okay which will actually send a file and I'm gonna use path dot join we did this in the node course and I'm just going to get the current directory with double underscore dur name go into a folder called public and load a file called index.html alright so we want to create that so I'll create a folder called public and let's create a file in there called index.html and I'm just gonna put some boilerplate in here and it's just to my website my website alright so now if we go back to our browser here and I reload we get my website and if we look at the source code you'll see all of the HTML so we can load HTML files this way however this isn't ideal because we'd have to put a route manually for every single page if we want an about page a contact page all that stuff we'd have to put separate routes now if you want just an just a static server that serves just you know HTML CSS images stuff like that then Express actually comes with functionality to to make a certain folder a static folder and we want to make this public folder static so we don't even have to do this I'm just gonna actually going to just get rid of that for now and let's go ahead and set a static folder alright so the way we do this is we say app dot use okay uses a method that we use when we want to include middleware and I'm gonna show you how to write your own middleware in a little bit and what that is but right now I'm just going to include express dot static and then we want to point to the folder that we want to set as our static folder so I'm going to use path join and we'll get the current directory and then point to public ok so just that one line right there is setting this public as our static folder so we can actually now go back and reload and it still works now I can put any HTML file I want in here like let's say about HTML oops we want that in public and then I'm gonna just copy the index paste that in here let's go ahead and just change this to about and now if I go back and I go to slash about dot HTML there it is so we can do create as many HTML pages as we want now we can also create CSS files so if I want to put a CSS folder and say style dot CSS we'll just do like body set it to a dark background and let's do color white oops okay now go to index.html and we can just simply include a link to CSS / style CSS I'll also put it in the about page and now if I go back and reload you'll see that the CSS is in effect okay I can go to slash about now I'm sorry Bo it has to be dot HTML for the static server now if you took the node crash course basically this is what we did and we wrote a whole lot of code to be able to do it we had to handle the content type ourselves we had to handle loading the HTML files loading the CSS any images stuff like that with express when we when we deal with this static folder we don't have to do anything except just put the files in here and it will just work and all we have to do is write this these few lines of code okay so that's how we can create a static server that just serves you know just regular HTML files it's usually not what you're going to use Express for for the most part you're gonna build either jason api's so that you can connect from a front-end like react or something like that which I'm going to show you how to do or you want to render templates where you can insert dynamic data so you can create a dynamic app rather than just a static website alright so I'm going to I'm going to leave the static folder there in case we want to use it but let's go ahead and move on and let's create a route here so I'm gonna say app dot get and let's do slash API slash members okay so basically I want to create kind of just a simple REST API we're not going to be dealing with a database we're just gonna have a hard-coded array but it's the same principle when we're dealing with routes and responses and all that stuff so let's put in request response I'll use an arrow function and what I want to do is return some jasons so I'm actually gonna just hard code right here actually I'll copy and paste it just so I don't have to type it all out so I'm just gonna create an array of members so basically just users so we have an ID a name and email and a status okay we have three of them so I want to return this as Jason when we hit this route right here so we could we could hit it with you know react or view or angular we could hit it with postman which is what we're gonna do and we can get these members so let's go ahead and just do a res jason okay if we want to return Jason we just do res dot JSON and we can simply just put in members okay now we don't even have to do like jason stringify or anything even though these are JavaScript objects because this will take care of it okay so let's go ahead and save that and then I'm gonna open up postman make sure this is a get request and let's say HTTP localhost port 5000 slash API slash members and there we go so we get our three members okay so it's as simple as that now since this is only one expression here and we're using an arrow function I don't even need to to use curly braces we can just go like that okay and I'll just put a comment here that this route gets all members okay now I want to just take a second before we get into creating other routes and talk a little bit about middleware so as I said middleware functions they're just functions that that have access to this request and response and you can actually you know change things you can add things and so on so what I want to do is just create a simple logging middleware function so let's see actually you know what let's put this let's put these in a separate file just so it doesn't clog this up so I'm just gonna copy or cut those out create a file called members dot J s uppercase M because it's basically our model and paste that in and then we just want to export this we want to do module dot exports equals members okay and then we can just bring it into our index J s so we'll say Const members equals dot slash I'm sorry I wanted to require and it's do dot slash members okay so that should still work let's test it out real quick and it still works okay so as I was saying and then create just a simple middleware function so let's go right here and let's say cons I'm going to use an arrow function but you could use a regular function I'm gonna call this logger okay now when you create middleware it takes in the request response and then next okay and you always want to call next last so that you can move to the next middleware function that's in the stack okay so this is like I said this is an arrow function and all I want to do is log something so for now I'm just gonna say let's just say hello okay now in order to initialize your middleware actually I need to do next like I just said in order to initialize it we do app dot use and we're just gonna pass in logger okay let's say in it middleware so now if I go and I hit actually go back I'm gonna go to postman and just make a request and then go back and look in the console and you'll see hello okay so every time we make a request this middleware is gonna run and we could do absolutely anything in here we could execute any code we want we have access to the request and response so what I'm gonna do is I'm gonna log the URL that's hit and the date okay so we can actually have access to certain parts of the URL with the request objects I'm gonna put some backticks in here and I'm gonna say request dot protocol okay so this is going to give us HTTP and then I'm gonna do colon slash slash and then we want to get the host which is also available in the request object so we'll say request dot I'm sorry we need to do request get host we can get different parts of the URL and then we want the what's called the original URL which is the page so after that let's do request dot original URL all right so let's just see what this gives us if we save this and then we go back to postman send a request and look in the console it gives us undefined that's because I did res requests and yeah it should work so let's try that again okay so now we get the whole URL that's hit 5,000 API members now I also want to put the the date and time formatted after it so I'm going to use a third-party package called moment which will it deals with dates it deals with date formatting so I'm going to stop the server real quick and just do an NPM install moment and then we'll run our server again and let's bring in a moment so Const moment equals require moment and then after the URL here I'm just gonna put a colon and then I'm gonna say moment which is a function so we actually have to put this in the syntax and then we just want to call dot format which is a method okay and that should give us the current date format it so I'm gonna save that and I have prettier installed so it just kind of formatted this a little bit and if I go back and we make another request and we go and look in our console now we have the URL and the date okay so we could go further and we could save this to a file with the FS module if we wanted to you but my point is you can do anything you want in terms of middleware and you have access to these requests and response objects this is not something that's very advanced but it is doing something so I'm gonna actually put this in a separate file because I want to save pretty much everything I do so you guys have it as a reference so I'm just gonna create a folder called middleware and let's create a file called logger dot j/s alright and then we'll just grab this whole thing here this whole function cut that out and put it into logger j/s and we just want to explore so module dot exports equals logger ok and then we'll bring it into our index j s const logger and we want to set that to require and go into middleware slash logger ok and i'll save that and it should still work so if i make a request moment is not defined so the logger file doesn't a moment included so I'm gonna just cut it from here because we don't need it in here anymore so we'll just bring it into vlogger okay so now oops to keep opening Chrome so we'll go ahead so that works and then it's still logging down here okay and as many requests as we make if I just hit this a couple time couple times it'll keep logging alright now I don't actually want this to keep running so I'm just gonna comment out the initializer here so it doesn't actually log anymore but now you can see how middleware works how its implemented so we're gonna move on now the next thing I want to do in terms of our little API that we're creating is I want to get a single member okay an individual member so I'm gonna do say get single member so we'll say app get we want to get requests and we want to go slash API slash members and then we need to specify an ID okay we want to get the member by their ID so we're gonna say : ID which is a URL parameter okay and we can use the request object to grab whatever is in there so let's put our callback request response all right now like I said we can use this request object to get whatever is in there so I'm just gonna do a quick res dot so we'll just do a res dot sin just so I can show you how this works so if we say request dot params dot and then we can get any parameter that's passed in here so we want the ID okay now if I go to postman and I'm just gonna open up another tab and let's look at localhost 5,000 slash API slash members slash and you can see it gives us four okay so obviously that's not what we want we want to get if we want the member with the idea for which there but let's go ahead and get rid of this and let's just do a res dot Jason and I mean there's different ways we could do this I'm gonna use the filter method which will take an array and just filter things out with filter it out based on a condition so we'll take the members array filter okay so it's a method we tack on to it I'm sure most you guys have used filter before and then let's say for each one we'll call it member and use an arrow function and we'll say we want to return the member dot ID that's equal to the request dot params dot ID now we're gonna have an issue here so let me just show you if we go to postman we know that there is an ID of one so let's go ahead and send that and notice we don't get anything back so the reason for this is the ID is a number okay and our members array you can see the IDs and number however request params ID sends it as a string so we simply need to we need to wrap this in parse int and the reason for that is I use triple equals which means that this type has to also match this type so let's go ahead and do parse int and wrap that all right so now if I go back to postman and we send that again we get the ID of one okay if we do two you should get the user with the other member with the ID of two now let's take it a step further because if we do like let's say six it gives us nothing back which may be fine it all depends the way you construct your API is completely up to you or whoever it's up to but what I want to do is is give a message saying that there is no member with this ID okay and there's a lot of different ways you can do this I'm going to use the sum method so I'll create a variable here called found and this is just JavaScript everything that I'm doing in here aside from this request params ID is just JavaScript so let's say members dot some and same thing it's a high order array method we're gonna pass in member and we're gonna say member dot ID equals and we're doing the same thing we're doing here we're just checking to see if it exists because what some does is it it'll run this condition and give us a true or false based on on this right here okay so if it doesn't exist this will equal false if it does exist it'll equal true and then I'm just gonna add an if statement here so if found then let's just move this up here and then we'll say else so how do we want to handle this if there isn't a member of that ID now this is where HTTP statuses come in if we just do res dot jason and everything is fine you'll see that in postman it's a two hundred status which means everything's okay now the status i want to give if there isn't a member with that ID is a four hundred because that means that it's a bad request it means they didn't give us the correct request information to give them a correct response so we're gonna do res dot status so we can set the status to something different and we're gonna set it to four hundred and then we can just do dot jason and we can tack in whatever we want usually some kind of message so I'm just gonna say message member not found okay actually you know what we could even do this we could you could use backticks here oops so we use back ticks and we'll say let's say no member with the ID of and then we can just put in our request dot params dot ID so I think that's kind of a cleaner way to handle the response so now let's try this again we'll try to get members 6 and we get message no member with the ID of 6 and notice we also are giving a 400 bad request so let's go back in and now I want to be able to actually create a member now having all these routes in our index file it's getting kind of cramped up actually I'm going to close all these up we don't need these open so this is getting cramped up so we can use the router that comes with Express to put all of our all of our similar routes into a single file so I'm going to create a folder in our route here called routes and inside routes I'm going to create a folder called API just because not all of our routes might they might not all be api's where we're serving Jason we may have routes where we're actually serving server side templates so I usually when I'm building an API I'll usually create an API folder and then let's create a file called members Jas and everyone does things different that that's the thing with Express as I said it's very unappealing to structure your files and your code however the hell you want so you're gonna see it's going to be different from application to application so let's take both of these routes the all members in single member and let's cut that out and let's put it in members all right now in order to use the Express router in order for this to work we need to do a couple things here so we need to bring in Express so that we can use the router okay so now we can say Const router and we're gonna set that to Express dot router capital R okay so when we use the router we actually when we make our rack we're we handle our requests we use router dot and then the type instead of app okay so we'll do router get router dot cat now we're dealing with the members so instead of having members in our index let's cut that out and let's bring it into the members route file and then the last thing we want to do here is export so it's say module dot exports equals router all right now in order for this to actually work we're gonna go into our index J s and let's go down to the bottom here we'll go right let's go right below the static folder and we need to do an app dot use and then put the route that we want which is going to be slash API slash members so basically like the parent route and then we want to set a second parameter requiring that file that we just created so it's gonna be let's see dot slash routes slash API slash members okay now since we have the route here API members we don't need it here or here so we just replace it with a slash okay so that'll be slash and then this one will be slash ID okay so now this should work so we'll go back to postman let's see members dot some is not a function that's because members is now in a different location since we moved it so we need to go dot dot slash outside of the API folder and then dot dot slash outside of the routes folder okay so we'll go back know ID with six let's try one okay that works if we go over here and just do API members we get all of our members alright so just cut we just kind of cleaned everything up a little bit so now we just have this one line here we can just say members API routes all right so let's move on and let's create a member so I'm gonna go down here and say create member now whenever you create something on the server or you're adding to a database whatever you want to make a post request in most cases so to handle a post request we're gonna say router dot post instead of router doc yet okay whether it's a form submission or whether it's getting sent with the fetch API or Axios or something like that and then in here we're gonna do just slash okay because we want to hit the slash API slash members now even though we're using it right here we can still use it here because we're using different HTTP types here so our methods I should say so we have get in post okay so we can use the same route as long as they're different methods so let's create our arrow function now we want to be able to send data and when we when we get that data it's gonna be in the request object so for now I'm just gonna do a res dot send and I want to send a request stop body okay now we're gonna go to postman let's open up a new tab and make a post request to HTTP 5,000 API slash members now we want to send some data I want to be able to send an e the email and the name for the member so under headers let's create the content type of application slash Jason because that's the type of data we're sending and then in the body we'll go ahead and choose raw and let's put in some jason so we'll send a name let's do I don't know Jake Smith and then we'll do an email of Jake Gmail all right now if I send this if we look down here we get nothing back we get a 200 response but nothing back and the reason for that is we need to include t use a body parser so that we can parse the data that we're sending in the body now you used to have to install a separate body parser it was a third party package that you had to install however with the newest version of Express we don't have to do that there's one included with Express we just have to initialize it as middleware so we're going to go back into index j s and let's say app dot use let's just put a comment here let's say body parser middleware and we say Express dot JSON ok so that will allow us to just handle raw jason now we also want to handle form submissions so we're also going to do Abdul I use Express dot URL encoded and we just pass in an object with extended and set that to false so that way we can handle URL encoded data so now if I go back and we send this again you'll see that when we do the res dot send for the request body it gives us the data that we just sent ok so that's coming from this now obviously we don't want to just send that back we want to create a new member so I'm gonna create a variable here called new member and set this to be an object now usually when you're dealing with IDs in your using a database like MongoDB or our MySQL or Postgres we're not using a database so I'm going to actually install something called UUID which will generate a random ID so I'm gonna just do NPM install UUID and let's just go ahead and run our server again and then let's bring in that package so UUID okay now for the ID I'm just gonna set it to you UID dot version 4 which is a method and that will just generate a random universal ID all right and then for the name we want to get that from request dot body okay so we want request dot body dot name the email we're sending in the body as well so request dot body dot email and then status I'm just gonna set status to active okay so it'll always be set to active when a new member is created all right so let's say we have this object now we want to add this new member on to our array however I want to make sure that the name and the email are sent with the request so let's go ahead and do a quick check here so we'll say if not new member dot name or not new member dot email then let's return or we can just do res dot status let's do a 400 because again it's a bad request because they should be sending a name and an email and then we'll say Jason and let's do message and we'll say please we'll just say please include a name and email all right and then down here let's do a members actually it's doing else actually one thing I'll mention here is if we don't do an else here we're gonna get an error that says headers are already sent and if that's the case and you could just do like that and that way we don't need an else so let's just do members dot push okay so we're taking the members array which is just our hard-coded array and we're pushing on the new member alright now that we'll add it to the array however we need to send back a response and again it's up to you what you want is what you want to respond with you could respond with the actual just the new member itself what I'm gonna do is return the entire array of members that includes the new one so I'll just say res dot jason and let's pass in members okay so let's save that and then let's go back here let's try it first without an email so we'll send that so we get please include a name and email and now we'll go ahead and include the email and send and we get all of the current members and our new one okay so we have Jake Smith Jake it gmail active and then this is the ID that UUID generated for us alright cool so the next thing I want to do is I want to be able to update a member now when you're dealing with a real API obviously you're gonna have a database you're not just going to have a file with your data and I don't want to get into that because that's something it's just I want to stick to Express as much as I can without going into you know MongoDB or certain databases but what will happen is you'll just Brill install a package like Mongoose which is an object relational or object data mapper for MongoDB and you would connect to your database and instead of just pushing on like this you would do something like members you take your members model and call save like that and then pass in new member so some kind of syntax like that whether using MongoDB or you're using like sequel eyes which is a great Oh RM for MySQL and Postgres alright so we're just dealing with hard-coded data so anyways let's move on let's go down here and let's say update member and I'm just gonna copy the whole get single member here because it's gonna be similar we want to check and make sure that there is a member with that ID okay however it's going to be a put request when you update something on the server in most cases it's going to be a put request so we're gonna check to see if the member exists if it doesn't we're gonna do the same no member with the ID however if it is found then we want to first of all let's create a variable called update member and set that to the request dot body okay so we'll get the the email and the name from this request stop body and then we basically want to loop through the members we have and then check to see if it matches this ID if it does that's the one we want to update so let's do let's do a for each okay and like I said there's a lot of different ways you can do this this is just JavaScript I mean I didn't have to do all this I guess but I'm just trying to give you an idea of how how to create a simple API so let's do members for each member will put an arrow and then let's do an if statement here and we'll check to see if the member dot ID is equal to parse int request params dot ID if it is that's the one we want to update so we'll just set member dot name to request body dot name and then we'll set member dot email to request body dot email all right now the problem with this is they may will update just the name and not the email or vice versa so we should probably check to see if it's if their name and email are actually sent so what we'll do is use a ternary operator let's say updated member dot name oops dot names so if that's included then let's use that and I didn't I actually I didn't mean to do this request body I meant to do the updated member name so let me just get rid of that alright so updated member name else then we're just gonna keep the member name whatever that is okay I will do the same thing here I'm just gonna grab this except we're gonna do email okay so just to reiterate we're gonna make a request to API members ID a put request we're gonna send along a name in email or either one we had any if anything we want to update basically check if it's found if it is we're going to put the request body in this variable we're gonna loop through our members check to see if the ID is equal to the ID that is passed in here if it is we know that's the one we want to update so then we're gonna set the member name depending on if the name was sent with the request if it was we'll set it to the new name if it wasn't we'll keep the old one okay same thing with the email now we need to send back a response so what I'm gonna choose to do here is let's see I'm gonna just do a res dot Jason and I'm gonna send a message that the member was updated and I'm also gonna send the member itself okay which this is the same as doing this since these are both the same we can just do member once all right so let's save that now let's go back to postman and I'm gonna copy this URL open up a new tab and make a put request to slash let's do slash one that's the one we'll update and then we'll add in our content type of Jason go to body and let's change the name I think what's the first amount let's see I mean just check this John Doe so let's change John's email address to let's say a yahoo address so just do email and set it to John at yahoo.com and let's send and see what we get back so we get member updated and everything is the same except for the email okay so we have just updated the email the name is the same everything else is the same alright and obviously this stuff is just in memory there's no database it's not getting persisted but again the requests the response all that stuff is gonna be the same it's just this functionality this stuff here will be different if you're using a database okay so let's see what do we get the left we can get members you can get a single member create update so we just have delete left which is should be pretty easy so I'm gonna actually copy the get again and let's say delete remember and this is gonna be a delete request so we want to do router dot delete okay we need the ID because we need to know which one to delete we'll keep this whole found thing here and then instead of just returning that which actually I do want to do but let's see instead of doing this we want to filter out the one with the ID so we're gonna say not equal to okay we're still gonna use filter we'll say not equal to but let's let's also put a message so in this res dayson what I'll do is say message member deleted and then oops just put a comma here and then let's just say member actually let's return yeah all the members because that's what this is gonna do it's gonna return all the members except the one that was deleted all right and then we just want to and put our curly brace here all right so let's save that prettier fixed it up so you can see it a little better and now if we go when we make a delete request to this let's delete the first one John Doe and send we get member deleted and then if we look at our members array John Doe is gone he's not there because we used filter to filter the idea of one out all right so we have a crud API where we can create read update and delete so now I want to move on to rendering templates using a template engine and there's a lot of different template engines that you can use we're gonna go ahead and use express handlebars so if we go to the github for that we need to install this so install Express handlebars and basically we can have a views folder and we can create a main layout to wrap everything and then we can create individual views and we can render them using red start render okay so this is going to be a lot easier than what we just did with the API and stuff so let's go ahead and close up our members routes and inside actually let's install it first so I'm going to just stop our server let's do an NPM install Express - handlebars okay we'll go ahead and run our server again and then in the index J s I'm gonna go ahead and bring this in let's go right here and let's say Const exp so express handlebars HBS and this is in the documentation all this stuff let's require Express handlebars should be - alright now this takes we have to add some middleware here so that it knows to use handlebars so let's go right here and just say handlebars middleware so first thing we need to set the engine so app app engine and let me just show you that this is in the documentation so I'm just doing this right here in fact they can just copy this so we're said setting the engine the view engine our template engine - handlebars and then we're just passing in this exp HBS and here we're setting the default layout to a file name of main so when we create our layout we want to call it main dot handlebars and then here we're just setting the view engine okay so we need these two lines in order to use handlebars so let's save that and let's go into our folder structure and create a folder call views and inside views will create a folder called layouts and here's where we want to create our main file so we'll say new file main dot handlebars okay now this is a layout that's gonna wrap everything so we want our doctype our title all that stuff will just say members app and let's just grab bootstraps so that we can make this look decent now for let me just explain for the most part you're you're not really going to do this where you have a JSON API and then you also have server rendered templates it's usually going to be one or the other you're usually going to either be building an API so that you can have react or view or something on the front end and you're just serving Jason or you're gonna have a complete server-side app where you use templates since this is a crash course I'm just trying to show you both as well as a static server the static folder that we did earlier so let's see let's go to get bootstrap and I'm just gonna grab the CDN here and let's go back here and just paste that in all right so in the layout wherever we want to output the rest of our views with handlebars we want to use triple curly braces and we want to put in body okay so that's gonna output any views now I just want to wrap this in a class of container just to keep it in and let's put a class of mt4 that's margin-top it's just they're just bootstrap classes and we're gonna put body inside there alright let's save that so now I want to create a few for the index page so inside views not in layouts but just in views I'm gonna create a file called index dot handlebars and for now I'm just gonna put an h1 and we'll just say members all right now if I want to render this I'll create a route so let's go let's go right here and say app because we're not in the router anymore we're in the main index so we'll say app dot get slash because I want this to render on the basically like the home page the index page and we just need to do res dot render and we can pass in index because we want to render the index view we'll just say homepage route all right so we'll save that and now if we go back to our application and reload we get members now the reason the static HTML file isn't showing is because we have static down here if I were to move this above our homepage route and save and go back now it's going to show that and like I said in most cases you're not going to have both like this this is it's just because it's a crash course and just I want you guys to have it as a reference so usually you're not going to do something like this well I shouldn't say that a lot of times you might have a static folder and you might have a form in one of the our HTML files that makes a post request whether it's to add to a database or something and then you know have like a pose slash contact or something like that all right so let's see let's add to our index handlebars file so we're gonna have actually I want to show you how we can pass data in so this render will take in a second parameter of an object and we can send in whatever we want so let's say like title and we'll put let's just put like member app and then we'll go to index and let's replace this now to use a variable with handlebars we just use double curly braces like that and we'll just say title so now if we go back we get members app all right I'm just gonna Center that so let's do class text Center will do margin bottom three okay now I want to also pass in the members and list them in this template so what we can do is bring in our members remember they're in the this members j/s file so I'll say Const members equals let's do slash members so now we have access to that array and I'm gonna pass it into the template here so put a comma will say members and that's all we need to do because doing this is the same thing now this is an array so in our template we want to loop through it and then output whatever we want whether it's just the name or the name and email and so on so I'm gonna put in each for here and we're just gonna say members and then let's do a ul and now I want to loop through the members we passed in and to do that with handlebars we do number sign each and then members okay and then we end it with slash each and then in here I'm gonna put an li and let's just do the name so we can say this dot name let's also put the email so I'll do colon and then we'll do this dot email now let's just add a bootstrap class so we'll say list group and then each list item will do list group item all right so let's save that let's go back and reload and you can see that it's loading those members okay now last thing I want to do is create a form so that we can actually make a request to our API to add a member from the form so I'll just put it in the same file we could create a whole new a whole new view for this a whole new template or whatever but I'm just gonna put it all in here so up here let's put a form let's give it a class of MB for it's just going to move everything down now the action is gonna be slash API slash members which we already created and then we want to make sure that the method of this form is a post all right and then we're gonna go ahead and add a form group class and then let's do a label we'll say this is for name and input with the with the class of form control these are just bootstrap classes now it's important to have a name attribute because that that's what's gonna get sent in the request body just like when we sent Jason from postman now we're sending it from a form okay that's why we have the URL encoded this right here this will handle the form data so name is going to be name all right now I'm gonna copy the form group because we also want the email so we're gonna change that email let's change change the type to email the name okay and then let's put a submit button so I'll do an input with the type of submit value we'll just say add member let's give it a bootstrap class of BTN BTN primary and it's due BTN block all right so go ahead and save that and let's reload this page here now we have a form now once I send this it's going to hit the sea routes API members it's going to hit the post right here so it'll create a new member it's going to get this and this from the forum and then down here it's gonna add the member and then it's going to return Jason which usually you wouldn't do if you're dealing with templates but I'll show you that after so let's go ahead and add let's say Kevin Smith Kevin and Gmail and send and you'll see that it returns Jason and it includes Kevin Smith now usually if you're dealing with templates you're gonna redirect you're not going to show Jason in an application like this if you're using server rendered views so what you would do here I'm just gonna comment that out you would most likely do something like res dot redirect and then redirect to slash same page alright so let's go back and then let's do Kevin Smith again and add member and what happened was it added the member and it redirected us back to slash which is this page here and you can see that Kevin got added ok if we add like Matt Johnson send and now that's getting added as well now I'm gonna go and just uncomment the redirect or comment the redirect and uncomment the Jason just because I want the API to work and then I'm just going to put a link in the the index page to the API so to the slash API slash members so I'll do let's do an a tag with the class of BTN BTN dash light do margin top four and will say slash API slash members and let's just say visit API alright so that way on this page we have a button that will go and show us the Jaison all right so I mean this is kind of a weird thing to build but I wanted to show you guys the different things you can do as far as building adjacent API as well as rendering templates on the server as well as having a static folder where you can just add HTML files CSS and so on now as far as authentication for the most part you're gonna you obviously you'll have some kind of database so let's say use MongoDB with Mongoose you're gonna create a user's model with a login a register and if you're building a full stack app like let's say you have view or react on the front end then you're probably going to deal with JSON web tokens where you pass a token back and forth to authenticate if you're using a template engine like we're doing here you can use passport J s in fact you can use passport with a full stack as well because if we look at strategies there's a bunch of different things including JWT passport local however is what you would use if you're just dealing with just Express just a server-side app and I do have a whole project using passport local on YouTube I do have some stuff with JWT as well on YouTube the best example that I can give you is my myrn stack course where we build a react application we use Express on the backend and we send JSON web tokens to authenticate which is it's it's kind of difficult it's definitely not something I would get into in this crash course but just to kind of give you an idea of how authentication works with Express there's there's no built-in authentication is basically what I'm trying to say so hopefully this gave you some insight on at least you know making requests handling responses handling HTTP status middleware templates stuff like that so if you made it this long thank you I know this is a long video most of these crash courses are but that's it so I will see you in the next video hey guys one of the best if not the best resource I can refer you to for starting a freelance business is at study web development comm slash freelancing the Creator Kyle shared it with me and I can personally vouch that this bundle is well worth it you get 130 page guide to freelancing and it comes with things like invoice templates client proposals HTML and CSS templates a portfolio website access to a private Facebook community and much more so use the code Brad 25 to get 25% off today
Info
Channel: Traversy Media
Views: 684,159
Rating: 4.9605875 out of 5
Keywords: express, expressjs, express js, node express, node.js, express framework
Id: L72fhGm1tfE
Channel Id: undefined
Length: 74min 1sec (4441 seconds)
Published: Fri Feb 22 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.