Express Js Crash Course

March 11, 2021

In this crash course we will dive into the Express JS framework for Node.js. I recommend first watching my Node.js crash course.

In this crash course we will dive into the Express JS framework for Node.js. I recommend first watching my Node.js crash course.

Crash Course Info

Date – Feb 22, 2019

Channel – Traversy Media

Transcript –

this video is sponsored by the ultimatefreelancing bundle by study webdevelopment comm which gives youeverything you need to start your ownfreelancing business including 130 pagein-depth guide invoicing and clientproposal templates website templates anSEO checklist and much more visit thelink in the description and use the codebrad 25 to get 25% off hey what’s goingon guys welcome to my Express crashcourse so a couple weeks ago I did a 90minute crash course on nodejs and thisis the next step seeing that Express isthe most popular web framework for nodeand even if you’ve worked with Expressbefore I’d still encourage you to watchbecause you’ll most likely learnsomething new somewhere along the way sowe’re gonna quickly look at some slidesand then we’ll jump in and we’ll startto look at how Express works so let’sfirst talk about what Express is it’s avery fast uh opinionated and minimalistweb framework okay so we all know whatfast means it’s it’s it’s veryhigh-performance unup enya natedbasically means that it’s it’s not ahigh level framework such as laravel forPHP or Django for Python it’s very basicat its core and it doesn’t assume thatyou’re gonna build your app or API inany certain way with any certain designpattern you have absolute full controlof how you handle your requests to theserver and how you respond and that’salso what makes it minimalist now I’msure most of you know this but Expressis a server-side or a back-end frameworkso it’s not comparable to client-sideframeworks like react or angular or viewin fact it’s it’s often used incombination with these frameworks tobuild very powerful full stack web appsmany times you’ll build out the API withExpress so that it takes requests fromthe front end and then it serves backdata usually in JSON format and then youcan do what you want with it in thefront end to render your your basicallyyour client side views now you can alsorender views with express using eitherjust plain HTML or you can use atemplate engine like handlebars or pugso there’s a lot of different optionswhen it comes to building web apps usingExpress so let’s look at why we woulduse Express well for one thing it makesbuilding node web apps about a hundredtimes easier if you watch my node crashcourse and you built out the simple webserver there was quite a bit of codethere to do to do something very verysimple we had to manually grab the URLload the file check the content type itwas very tedious Express makes handlingrequests very simple and it’s much muchless code so like I said Express is usedfor both api’s that serve JSON data aswell as back-end applications thatrender pages on the server okay it’sexciting like I said it’s extremely fastit gives you a ton of freedom it’s byfar the most popular framework someother examples of node frameworks arekoa happy Jas and Adonis which are allgreat but they’re nowhere near aspopular as Express koa and happy Jas arevery similar to Express however Adonisis much higher level in my opinionAdonis is very similar to laravel forPHP and it gives you a lot more but youalso don’t have as much freedom and it’sa much larger framework so the nextadvantage is is true for just nodeitself and that’s that it’s it’sJavaScript so if you’re building a fullstack app with like react you couldyou’re still using JavaScript on theserver side so there’s no need formultiple languages so that’s always anadvantage but that’s not just forExpress that’s any anything that has todo with node so as far as what youshould know before starting to learnExpress I would say at the very leastyou should just be comfortable withJavaScript I’d also suggest having atleast some basic knowledge of node aswell as NPM which is the node packagemanager I’m not saying you have to be anodejs pro but at least watch you know acouple tutorials so you understand whatit is maybe look at some of the coremodules that are included and so onalright so some other things that canhelp you out is knowing about HTTPknowing the status codes you’re dealingwith requests you’re gonna have to sendback responses so it’s helpful to knowwhichwhich type of response you should sendback Jason if you’re dealing with youknow building api’s high-order arraymethods arrow functions promises all thenewer features of JavaScript they’recommonly used with known as well so Iwould suggest getting familiar with thatstuff all right so let’s quickly look atjust the basic syntax of a web server sothis is the absolute bare bones to get aserver to run in the browser sobasically we just bring in Express atthe top using the the common j/s modulesyntax note you can’t use the import thees2015 modules with node by default justyet if you do want to use it you’ll haveto use something like babel to compileit how otherwise you’re going to usethis syntax and then to initializeExpress you just set a variable to theexpress method here usually called appand then you create your endpoints so inthis case we’re accepting a get requestto the index route which is the slashand then we just have a callbackfunction that takes in a request and aresponse which we’ll talk a little bitabout in a second and then we just dowhatever we want in this case we’re justresponding with the text of hello worldand of course we need to listen on aport so in this case we’re listening onport 5,000 so if we went to localhostport 5000 in our browser we would seehello world okay and of course you cancreate routes to whatever you want ifyou wanted to do slash users or whateverand you can also include parameters andwe’re going to get into all that stuffso within your route you can do justabout anything fetch data from adatabase you can use MongoDB is verypopular to use with node but you canalso use postgrads MySQL there’sthird-party packages for just about anydatabase okay you can load pages you canreturn JSON data you have full access tothe request and response now the requestand response objects are very importantthe request object represents the HTTPrequest properties for things like URLparameters query strings any data that’ssent within the body the HTTP headersall this stuff is included in therequest you can also create somethingcalled middlewarewhich I’ll talk about in the next slidewhere you can change or add things tothis object and then the response objectrepresents the HTTP response and in it’sup to you to use this object tobasically send back you know JSON datado you want to render a template so youcan do multiple things with thisresponse object if you want to redirectyou can do rezident redirect so we’regonna look at more in-depth into both ofthese objects as the course goes on andthen we can parse any incoming data withthe body parser that’s included withexpress also we don’t have to put all ofour routes in one file Express has arouter so that we can store routes inseparate files and then we can justexported alright so the last thing Iwant to talk about real quick ismiddleware this is something that seemsto confuse a lot of people middlewarefunctions are they’re just functionsthat have access to the request andresponse objects okay just like we dowithin routes Express has its ownmiddleware and so do you knowthird-party packages that you install wecan also write our own middlewarefunctions which I’ll show you how to domiddleware is is capable of executingany code making changes to the requestand response objects editing the I’msorry not editing ending the responsecycle also you have to call the nextmiddleware in the stack so when youwrite a piece of middleware you’ll calla next function so you can just think ofit as kind of a stack of functions thatexecutes whenever a request is made tothe server and you can do differentthings within those functions that’s thegist of italright so enough talk let’s jump init’s much easier to see examples ratherthan me try to explain it so we’re gonnajump in we’re gonna look at pretty muchall the fundamentals of the Expressframework alright guys couple thingsbefore we get started obviously you’regonna have to have no js’ and installedon your system if you don’t just go tonode.js org and go ahead and downloadand install it now this is the Expresswebsite Express j/s comm which haspretty good documentation hasguides we are using version 4.16 pointfour in this crash coursehowever version five is in alpha at themoment if version five is stable by thetime you watch this you should still bealright because most of the syntaxeverything that’s on the surface ispretty much the same so you should bealright even if even if version 5 is anelf I’m sorry is stable so I’m gonna beusing postman which is an HTTP client tomake requests to our serverokay so postman can make get put postdelete requests so I’ll be using that soif you’re going to follow along I wouldsuggest downloading that as well fromfrom get postman com ok so I’m gonnajump into vs code which is the texteditor I’m using of course you can useany text editor you want I’ll be usingthe integrated terminal as well as faras you know installing packages andstuff like that so I just have an emptyfolder called Express Express crashcourse and first thing we’re gonna do iscreate a package dot Jason so I’m gonnado NPM an it and I’m just gonna add onthe dash Y flag so that I don’t have toanswer any questions ok and that you cansee that that creates a package.jsonfile now we’re gonna want to installExpress there’s a couple things that I’mgoing to install throughout this coursebut right now I’m just going to installExpress so I’m gonna say npm install ori express okay so that gets added to ourpackage jason and now i’m gonna createour main entry point file which i’mgonna call index dot JSPreally doesn’t matter what you call itso here we’re just gonna start off bycreating just a simple Express serverand just make this a little smalleralright so we’re gonna first bring inExpress so we’re gonna create a variableand we’re gonna set it to requireExpressall right and then what we want to do isinitialize a variable called app withexpress all right now this app has abunch of properties and methods one ofwhich is listen so that’s what we needto use to actually run the webserver wewant to listen on a port okay now what Iusually do is create a variablesometimes in a separate config file butI’m just going to create it here and wewant to set this to a port number so Iwant to use 5,000 in development howeverwe want to also add here process dot envwhich means that we want to look at theenvironment variables we want to lookfor one called port okay and then wejust want to put or so double pipecharacter is going to be or now thereason we put this is because when wedeploy the server isn’t most likelyisn’t going to run it on 5000 it’s goingto have the port number in anenvironment variable so we want to checkthat first okay if that’s not availablethen we want to run on 5,000 okay sothen down here and listen we just wantto put in our port variable and we canalso add a callback as a secondparameter and I just want to do aconsole log because when we run ourserver I want it to let us know in theconsole that it’s running so I’m gonnaput in some back ticks and I’m gonna sayserver started on port and then we’ll goahead and put in our port variable okayso just doing this will actually run aserver so I’m gonna save it and I’ll godown here and I’ll type in node and thenthe name of the file which is index andyou can see server started on port 5,000all right now if I go to 5,000 solocalhost and we want to go to colon5,000 we’re gonna get this message herecannot get slash so slash is the routefor the index page and it’s basicallyjust saying that it can’t find a routehandler for this slash okay if we try togo to like slash a boat it’ll say cannotget slash above because we haven’tcreated any routes any endpoints solet’s go back in and let’s create aroute here so to create a route we wantto use Appand then the type of requests that wewant to handle now when you just go to aweb page that’s a get request so we wantto do app get and then the road is gonnabe just slash and then the secondparameter is gonna be a function okay ifyou want to use this syntax you can dothatand pass in your request and responsehowever I’m going to use an arrowfunction so I’m going to get rid of thefunction keyword and just gonna put anarrow here alright nowthe every route we create is gonna we’regonna have access to this request andresponse object we’re gonna look intoboth of these as as we move along hereright now what I want to do is just takethe res the response object and it has amethod called sin that will just sendsomething to the browser so some text orwhatever so I’m just gonna say helloworld okay we could actually put HTML inhere so if I wanted to put an h1 wecould do that and we’ll save it now if Igo back and I reload notice that it’snot working and the reason for that isby default we have to restart ourservers down here we’ll do control C andthen run node index again and then if wego back we’ll get hello world now it’sjust the h1 if we look at the sourcecode oops don’t open that let’s look atthe source here and you can see it’sjust an h1 there’s no doctype nothinglike that there’s no content type sothis is obviously this isn’t what wewant to do I’m just showing you this asan example so let’s head back in and Idon’t want to have to keep resetting theserver every time we make a change sowhat I’m gonna do is install a packagecalled node Mon which will constantlywatch our server so we don’t have tokeep reloading so I’ll ctrl C to stopand let’s do NPM install and I’m gonnaadd dash D because I want to installthis as a dev dependency and then nodeMon okay it’s a dev dependency becauseit’s only for development we’re notusing it in production all right so nowwe have node LAN installed now to use itwe’re going to go into our package Jasonand we need to create a scriptokay so we’re gonna actually create twoscript one is gonna be–start which isjust simply going to run node index sothat will most likely be used indeployment and then for dev I’m going tocreate a script called dev and we’regonna use node Mon index okay and thedifference is node index you’ll have tokeep resetting the server every time youmake a changeno lon will constantly watch it so we’llsave this and then let’s go down hereand run npm run dev okay so you can seeit’s running on 5,000 however node mamanis running so if I were to go here andlet’s say add some exclamation marks andsave and go back and reload you can seethat the changes are made I don’t haveto reset the serverokay so node Mon is an extremely handytool now as far as what we send as aresponse we have a bunch of differentoptions obviously we have send but we’renot going that’s not used too much wecould send a file a single file if wewant I’ll show you how to do that wecould send Jason with res dot JSON wecould do res dot render if we had atemplate engine we could actually renderan HTML template where we could actuallyput variables in and stuff like thatsome examples of templates are pug whichI really don’t like I don’t like thesyntax I usually use handlebars or ejsif I’m rendering templates on the servernow what I want to do is bring in thepath module which is just a node.jsmodule to deal with file paths and I’mgonna just load an HTML file here so I’mgonna say instead of res send I’m gonnause send file okay which will actuallysend a file and I’m gonna use path dotjoin we did this in the node course andI’m just going to get the currentdirectory with double underscore durname go into a folder called public andload a file called index.html alright sowe want to create that so I’ll create afolder called publicand let’s create a file in there calledindex.html and I’m just gonna put someboilerplate in here and it’s just to mywebsite my websitealright so now if we go back to ourbrowser here and I reload we get mywebsite and if we look at the sourcecode you’ll see all of the HTML so wecan load HTML files this wayhowever this isn’t ideal because we’dhave to put a route manually for everysingle page if we want an about page acontact page all that stuff we’d have toput separate routes now if you want justan just a static server that serves justyou know HTML CSS images stuff like thatthen Express actually comes withfunctionality to to make a certainfolder a static folder and we want tomake this public folder static so wedon’t even have to do this I’m justgonna actually going to just get rid ofthat for now and let’s go ahead and seta static folder alright so the way we dothis is we say app dot use okay uses amethod that we use when we want toinclude middleware and I’m gonna showyou how to write your own middleware ina little bit and what that is but rightnow I’m just going to include expressdot static and then we want to point tothe folder that we want to set as ourstatic folder so I’m going to use pathjoin and we’ll get the current directoryand then point to public ok so just thatone line right there is setting thispublic as our static folder so we canactually now go back and reload and itstill works now I can put any HTML fileI want in here like let’s say about HTMLoops we want that in public and then I’mgonna just copy the index paste that inhere let’s go ahead and just change thisto about and now if I go back and I goto slash about dot HTML there it is sowe can docreate as many HTML pages as we want nowwe can also create CSS files so if Iwant to put a CSS folder and say styledot CSS we’ll just do like body set itto a dark background and let’s do colorwhite oopsokay now go to index.html and we canjust simply include a link to CSS /style CSS I’ll also put it in the aboutpage and now if I go back and reloadyou’ll see that the CSS is in effectokay I can go to slash about now I’msorry Bo it has to be dot HTML for thestatic server now if you took the nodecrash course basically this is what wedid and we wrote a whole lot of code tobe able to do it we had to handle thecontent type ourselves we had to handleloading the HTML files loading the CSSany images stuff like that with expresswhen we when we deal with this staticfolder we don’t have to do anythingexcept just put the files in here and itwill just work and all we have to do iswrite this these few lines of code okayso that’s how we can create a staticserver that just serves you know justregular HTML files it’s usually not whatyou’re going to use Express for for themost part you’re gonna build eitherjason api’s so that you can connect froma front-end like react or something likethat which I’m going to show you how todo or you want to render templates whereyou can insert dynamic data so you cancreate a dynamic app rather than just astatic website alright so I’m going toI’m going to leave the static folderthere in case we want to use it butlet’s go ahead and move on and let’screate a route here so I’m gonna say appdot get and let’s do slash API slashmembersokay so basically I want to create kindof just a simple REST API we’re notgoing to be dealing with a databasewe’re just gonna have a hard-coded arraybut it’s the same principle when we’redealing with routes and responses andall that stuff so let’s put in requestresponse I’ll use an arrow function andwhat I want to do is return some jasonsso I’m actually gonna just hard coderight here actually I’ll copy and pasteit just so I don’t have to type it allout so I’m just gonna create an array ofmembers so basically just users so wehave an ID a name and email and a statusokay we have three of them so I want toreturn this as Jason when we hit thisroute right here so we could we couldhit it with you know react or view orangular we could hit it with postmanwhich is what we’re gonna do and we canget these members so let’s go ahead andjust do a res jason okay if we want toreturn Jason we just do res dot JSON andwe can simply just put in members okaynow we don’t even have to do like jasonstringify or anythingeven though these are JavaScript objectsbecause this will take care of it okayso let’s go ahead and save that and thenI’m gonna open up postman make sure thisis a get request and let’s say HTTPlocalhost port 5000 slash API slashmembers and there we go so we get ourthree members okay so it’s as simple asthat now since this is only oneexpression here and we’re using an arrowfunction I don’t even need to to usecurly braces we can just go like thatokay and I’ll just put a comment herethat this route gets all membersokay now I want to just take a secondbefore we get into creating other routesand talk a little bit about middlewareso as I said middleware functionsthey’re just functions that that haveaccess to this request and response andyou can actually you know change thingsyou can add things and so on so what Iwant to do is just create a simplelogging middleware function so let’s seeactually you know what let’s put thislet’s put these in a separate file justso it doesn’t clog this up so I’m justgonna copy or cut those out create afile called members dot J s uppercase Mbecause it’s basically our model andpaste that in and then we just want toexport this we want to do module dotexports equals members okay and then wecan just bring it into our index J s sowe’ll say Const members equals dot slashI’m sorry I wanted to require and it’sdo dot slash members okay so that shouldstill work let’s test it out real quickand it still works okay so as I wassaying and then create just a simplemiddleware function so let’s go righthere and let’s say cons I’m going to usean arrow function but you could use aregular function I’m gonna call thislogger okay now when you createmiddleware it takes in the requestresponse and then next okay and youalways want to call next last so thatyou can move to the next middlewarefunction that’s in the stack okay sothis is like I said this is an arrowfunction and all I want to do is logsomething so for now I’m just gonna saylet’s just say hello okay now in orderto initialize your middleware actually Ineed to do next like I just said inorder to initialize it we do app dot useand we’re just gonna pass in logger okaylet’s say in itmiddleware so now if I go and I hitactually go back I’m gonna go to postmanand just make a request and then go backand look in the console and you’ll seehello okay so every time we make arequest this middleware is gonna run andwe could do absolutely anything in herewe could execute any code we want wehave access to the request and responseso what I’m gonna do is I’m gonna logthe URL that’s hit and the date okay sowe can actually have access to certainparts of the URL with the requestobjects I’m gonna put some backticks inhere and I’m gonna say request dotprotocol okay so this is going to giveus HTTP and then I’m gonna do colonslash slash and then we want to get thehost which is also available in therequest object so we’ll say request dotI’m sorry we need to do request get hostwe can get different parts of the URLand then we want the what’s called theoriginal URL which is the page so afterthat let’s do request dot original URLall right so let’s just see what thisgives us if we save this and then we goback to postman send a request and lookin the consoleit gives us undefined that’s because Idid res requests and yeah it should workso let’s try that again okay so now weget the whole URL that’s hit 5,000 APImembers now I also want to put the thedate and time formatted after it so I’mgoing to use a third-party packagecalled moment which will it deals withdates it deals with date formatting soI’m going to stop the server realquick and just do an NPM install momentand then we’ll run our server again andlet’s bring in a moment so Const momentequals require moment and then after theURL here I’m just gonna put a colon andthen I’m gonna say moment which is afunction so we actually have to put thisin the syntax and then we just want tocall dot format which is a method okayand that should give us the current dateformat it so I’m gonna save that and Ihave prettier installed so it just kindof formatted this a little bit and if Igo back and we make another request andwe go and look in our console now wehave the URL and the date okay so wecould go further and we could save thisto a file with the FS module if wewanted to you but my point is you can doanything you want in terms of middlewareand you have access to these requestsand response objects this is notsomething that’s very advanced but it isdoing something so I’m gonna actuallyput this in a separate file because Iwant to save pretty much everything I doso you guys have it as a reference soI’m just gonna create a folder calledmiddleware and let’s create a filecalled logger dot j/s alright and thenwe’ll just grab this whole thing herethis whole function cut that out and putit into logger j/s and we just want toexplore so module dot exports equalslogger ok and then we’ll bring it intoour index j s const logger and we wantto set that to require and go intomiddleware slash logger ok and i’ll savethat and it should still work so if imake a request moment is not defined sothe logger file doesn’ta moment included so I’m gonna just cutit from here because we don’t need it inhere anymoreso we’ll just bring it into vlogger okayso nowoops to keep opening Chrome so we’ll goahead so that works and then it’s stilllogging down here okay and as manyrequests as we make if I just hit this acouple time couple times it’ll keeplogging alright now I don’t actuallywant this to keep running so I’m justgonna comment out the initializer hereso it doesn’t actually log anymore butnow you can see how middleware works howits implemented so we’re gonna move onnow the next thing I want to do in termsof our little API that we’re creating isI want to get a single member okay anindividual member so I’m gonna do sayget single member so we’ll say app getwe want to get requests and we want togo slash API slash members and then weneed to specify an ID okay we want toget the member by their ID so we’regonna say : ID which is a URL parameterokay and we can use the request objectto grab whatever is in there so let’sput our callback request response allright now like I said we can use thisrequest object to get whatever is inthere so I’m just gonna do a quick resdot so we’ll just do a res dot sin justso I can show you how this works so ifwe say request dot params dot and thenwe can get any parameter that’s passedin here so we want the ID okay now if Igo to postman and I’m just gonna open upanother tab and let’s look at localhost5,000 slash API slash members slashand you can see it gives us four okay soobviously that’s not what we want wewant to get if we want the member withthe idea for which therebut let’s go ahead and get rid of thisand let’s just do a res dot Jason and Imean there’s different ways we could dothis I’m gonna use the filter methodwhich will take an array and just filterthings out with filter it out based on acondition so we’ll take the membersarray filter okay so it’s a method wetack on to it I’m sure most you guyshave used filter before and then let’ssay for each one we’ll call it memberand use an arrow function and we’ll saywe want to return the member dot IDthat’s equal to the request dot paramsdot ID now we’re gonna have an issuehere so let me just show you if we go topostman we know that there is an ID ofone so let’s go ahead and send that andnotice we don’t get anything back so thereason for this is the ID is a numberokay and our members array you can seethe IDs and number however requestparams ID sends it as a string so wesimply need to we need to wrap this inparse int and the reason for that is Iuse triple equals which means that thistype has to also match this type solet’s go ahead and do parse int and wrapthat all right so now if I go back topostman and we send that again we getthe ID of one okay if we do two youshould get the user with the othermember with the ID of two now let’s takeit a step further because if we do likelet’s say six it gives us nothing backwhich may be fine it all depends the wayyou construct your API is completely upto you or whoever it’s up to but what Iwant to do is is give a message sayingthat there is no member with this IDokay and there’s a lot of different waysyou can do this I’m going to use the summethod so I’ll create a variable herecalled found and this is just JavaScripteverything that I’m doing in hereaside from thisrequest params ID is just JavaScript solet’s say members dot some and samething it’s a high order array methodwe’re gonna pass in member and we’regonna say member dot ID equals and we’redoing the same thing we’re doing herewe’re just checking to see if it existsbecause what some does is it it’ll runthis condition and give us a true orfalse based on on this right here okayso if it doesn’t exist this will equalfalse if it does exist it’ll equal trueand then I’m just gonna add an ifstatement here so if found then let’sjust move this up here and then we’llsay else so how do we want to handlethis if there isn’t a member of that IDnow this is where HTTP statuses come inif we just do res dot jason andeverything is fine you’ll see that inpostman it’s a two hundred status whichmeans everything’s okay now the status iwant to give if there isn’t a memberwith that ID is a four hundred becausethat means that it’s a bad request itmeans they didn’t give us the correctrequest information to give them acorrect response so we’re gonna do resdotstatus so we can set the status tosomething different and we’re gonna setit to four hundred and then we can justdo dot jason and we can tack in whateverwe want usually some kind of message soI’m just gonna say message member notfound okay actually you know what wecould even do this we could you coulduse backticks here oopsso we use back ticks and we’ll say let’ssay no member with the ID of and then wecan just put in our request dot paramsdot ID so I think that’s kind of acleaner way to handle the response sonow let’s try this again we’ll try toget members 6 and we get message nomember with the ID of 6 and notice wealso are giving a 400 bad request solet’s go back in and now I want to beable to actually create a member nowhaving all these routes in our indexfile it’s getting kind of cramped upactually I’m going to close all these upwe don’t need these open so this isgetting cramped up so we can use therouter that comes with Express to putall of our all of our similar routesinto a single file so I’m going tocreate a folder in our route here calledroutes and inside routes I’m going tocreate a folder called API just becausenot all of our routes might they mightnot all be api’s where we’re servingJason we may have routes where we’reactually serving server side templatesso I usually when I’m building an APII’ll usually create an API folder andthen let’s create a file called membersJas and everyone does things differentthat that’s the thing with Express as Isaid it’s very unappealing to structureyour files and your code however thehell you want so you’re gonna see it’sgoing to be different from applicationto application so let’s take both ofthese routes the all members in singlemember and let’s cut that out and let’sput it in members all right now in orderto use the Express router in order forthis to work we need to do a couplethings here so we need to bring inExpress so that we can use the routerokay so now we can say Const router andwe’re gonna set that to Express dotrouter capital R okay so when we use therouter we actually when we make our rackwe’re we handle our requests we userouter dot and then the type instead ofapp okay so we’ll do router get routerdot cat now we’re dealing with themembers so instead of having members inour index let’s cut that outand let’s bring it into the membersroute file and then the last thing wewant to do here is export so it’s saymodule dot exports equals router allright now in order for this to actuallywork we’re gonna go into our index J sand let’s go down to the bottom herewe’ll go right let’s go right below thestatic folder and we need to do an appdot use and then put the route that wewant which is going to be slash APIslash members so basically like theparent route and then we want to set asecond parameter requiring that filethat we just created so it’s gonna belet’s see dot slash routes slash APIslash members okay now since we have theroute here API members we don’t need ithere or here so we just replace it witha slashokay so that’ll be slash and then thisone will be slash ID okay so now thisshould work so we’ll go back to postmanlet’s see members dot some is not afunction that’s because members is nowin a different location since we movedit so we need to go dot dot slashoutside of the API folder and then dotdot slash outside of the routes folderokay so we’ll go back know ID with sixlet’s try one okay that works if we goover here and justdo API members we get all of our membersalright so just cut we just kind ofcleaned everything up a little bit sonow we just have this one line here wecan just say members API routes allright so let’s move on and let’s createa member so I’m gonna go down here andsay create member now whenever youcreate something on the server or you’readding to a database whatever you wantto make a post request in most cases soto handle a post request we’re gonna sayrouter dot post instead of router docyet okay whether it’s a form submissionor whether it’s getting sent with thefetch API or Axios or something likethat and then in here we’re gonna dojust slash okay because we want to hitthe slash API slash members now eventhough we’re using it right here we canstill use it here because we’re usingdifferent HTTP types here so our methodsI should say so we have get in post okayso we can use the same route as long asthey’re different methods so let’screate our arrow function now we want tobe able to send data and when we when weget that data it’s gonna be in therequest object so for now I’m just gonnado a res dot send and I want to send arequest stop body okay now we’re gonnago to postman let’s open up a new taband make a post request to HTTP 5,000API slash members now we want to sendsome data I want to be able to send an ethe email and the name for the member sounder headers let’s create the contenttype of application slash Jason becausethat’s the type of data we’re sendingand then in the body we’ll go ahead andchoose raw and let’s put in some jasonso we’ll send a namelet’s doI don’t know Jake Smith and then we’lldo an email of Jake Gmail all right nowif I send this if we look down here weget nothing back we get a 200 responsebut nothing back and the reason for thatis we need to include t use a bodyparser so that we can parse the datathat we’re sending in the body now youused to have to install a separate bodyparser it was a third party package thatyou had to install however with thenewest version of Express we don’t haveto do that there’s one included withExpress we just have to initialize it asmiddleware so we’re going to go backinto index j s and let’s say app dot uselet’s just put a comment here let’s saybody parser middleware and we sayExpress dot JSON ok so that will allowus to just handle raw jason now we alsowant to handle form submissions so we’realso going to do Abdul I use Express dotURL encoded and we just pass in anobject with extended and set that tofalse so that way we can handle URLencoded data so now if I go back and wesend this again you’ll see that when wedo the res dot send for the request bodyit gives us the data that we just sentok so that’s coming from this nowobviously we don’t want to just sendthat back we want to create a new memberso I’m gonna create a variable herecalled new member and set this to be anobject now usually when you’re dealingwith IDs in your using a database likeMongoDB or our MySQL or Postgreswe’re not using a database so I’m goingto actually install something calledUUID which will generate a random IDso I’m gonna just do NPM install UUIDand let’s just go ahead and run ourserver again and then let’s bring inthat packageso UUID okay now for the ID I’m justgonna set it to you UID dot version 4which is a method and that will justgenerate a random universal ID all rightand then for the name we want to getthat from request dot body okay so wewant request dot body dot name the emailwe’re sending in the body as well sorequest dot body dot email and thenstatus I’m just gonna set status toactive okay so it’ll always be set toactive when a new member is created allright so let’s say we have this objectnow we want to add this new member on toour array however I want to make surethat the name and the email are sentwith the request so let’s go ahead anddo a quick check here so we’ll say ifnot new member dot name or not newmember dot email then let’s return or wecan just do res dot status let’s do a400 because again it’s a bad requestbecause they should be sending a nameand an email and then we’ll say Jasonand let’s do message and we’ll sayplease we’ll just say please include aname and email all right and then downhere let’s do a members actually it’sdoing else actually one thing I’llmention here is if we don’t do an elsehere we’re gonna get an error that saysheaders are already sent and if that’sthe case and you could just dolike that and that way we don’t need anelse so let’s just do members dot pushokay so we’re taking the members arraywhich is just our hard-coded array andwe’re pushing on the new memberalright now that we’ll add it to thearray however we need to send back aresponse and again it’s up to you whatyou want is what you want to respondwith you could respond with the actualjust the new member itself what I’mgonna do is return the entire array ofmembers that includes the new one soI’ll just say res dot jason and let’spass in members okay so let’s save thatand then let’s go back here let’s try itfirst without an email so we’ll sendthat so we get please include a name andemail and now we’ll go ahead and includethe email and send and we get all of thecurrent members and our new one okay sowe have Jake Smith Jake it gmail activeand then this is the ID that UUIDgenerated for us alright cool so thenext thing I want to do is I want to beable to update a member now when you’redealing with a real API obviously you’regonna have a database you’re not justgoing to have a file with your data andI don’t want to get into that becausethat’s something it’s just I want tostick to Express as much as I canwithout going into you know MongoDB orcertain databases but what will happenis you’ll just Brill install a packagelike Mongoose which is an objectrelational or object data mapper forMongoDB and you would connect to yourdatabase and instead of just pushing onlike this you would do something likemembers you take your members model andcall save like that and then pass in newmember so some kind of syntax likethat whether using MongoDB or you’reusing like sequel eyes which is a greatOh RM for MySQL and Postgres alright sowe’re just dealing with hard-coded dataso anyways let’s move on let’s go downhere and let’s say update member and I’mjust gonna copy the whole get singlemember here because it’s gonna besimilar we want to check and make surethat there is a member with that ID okayhowever it’s going to be a put requestwhen you update something on the serverin most cases it’s going to be a putrequest so we’re gonna check to see ifthe member exists if it doesn’t we’regonna do the same no member with the IDhowever if it is found then we want tofirst of all let’s create a variablecalled update member and set that to therequest dot body okay so we’ll get thethe email and the name from this requeststop body and then we basically want toloop through the members we have andthen check to see if it matches this IDif it does that’s the one we want toupdate so let’s do let’s do a for eachokay and like I said there’s a lot ofdifferent ways you can do this this isjust JavaScript I mean I didn’t have todo all this I guess but I’m just tryingto give you an idea of how how to createa simple API so let’s do members foreach member will put an arrow and thenlet’s do an if statement here and we’llcheck to see if the member dot ID isequal to parse int request params dot IDif it is that’s the one we want toupdate so we’ll just set member dot nameto request body dotname and then we’ll set member dot emailto request body dot email all right nowthe problem with this is they may willupdate just the name and not the emailor vice versa so we should probablycheck to see if it’s if their name andemail are actually sent so what we’ll dois use a ternary operator let’s sayupdated member dot name oops dot namesso if that’s included then let’s usethat and I didn’t I actually I didn’tmean to do this request body I meant todo the updated member name so let mejust get rid of thatalright so updated member name else thenwe’re just gonna keep the member namewhatever that is okay I will do the samething here I’m just gonna grab thisexcept we’re gonna do email okayso just to reiterate we’re gonna make arequest to API members ID a put requestwe’re gonna send along a name in emailor either one we had any if anything wewant to update basically check if it’sfound if it is we’re going to put therequest body in this variable we’regonna loop through our members check tosee if the ID is equal to the ID that ispassed in here if it is we know that’sthe one we want to update so then we’regonna set the member name depending onif the name was sent with the request ifit was we’ll set it to the new name ifit wasn’t we’ll keep the old one okaysame thing with the email now we need tosend back a response so what I’m gonnachoose to do here is let’s see I’m gonnajust do a res dot Jason and I’m gonnasend a messagethat the member was updated and I’m alsogonna send the member itself okay whichthis is the same as doing this sincethese are both the same we can just domember once all right so let’s save thatnow let’s go back to postman and I’mgonna copy this URL open up a new taband make a put request to slash let’s doslash one that’s the one we’ll updateand then we’ll add in our content typeof Jason go to body and let’s change thename I think what’s the first amountlet’s see I mean just check this JohnDoe so let’s change John’s email addressto let’s say a yahoo address so just doemail and set it to John at yahoo.comand let’s send and see what we get backso we get member updated and everythingis the same except for the email okay sowe have just updated the email the nameis the same everything else is the samealright and obviously this stuff is justin memory there’s no database it’s notgetting persisted but again the requeststhe response all that stuff is gonna bethe same it’s just this functionalitythis stuff here will be different ifyou’re using a database okay so let’ssee what do we get the left we can getmembers you can get a single membercreate update so we just have deleteleft which is should be pretty easy soI’m gonna actually copy the get againand let’s say deleteremember and this is gonna be a deleterequest so we want to do router dotdelete okay we need the ID because weneed to know which one to delete we’llkeep this whole found thing here andthen instead of just returning thatwhich actually I do want to do but let’ssee instead of doing this we want tofilter out the one with the ID so we’regonna say not equal to okay we’re stillgonna use filter we’ll say not equal tobut let’s let’s also put a message so inthis res dayson what I’ll do is saymessage member deleted and then oopsjust put a comma here and then let’sjust say member actually let’s returnyeah all the members because that’s whatthis is gonna do it’s gonna return allthe members except the one that wasdeleted all right and then we just wantto and put our curly brace here allright so let’s save that prettier fixedit up so you can see it a little betterand now if we go when we make a deleterequest to this let’s delete the firstone John Doe and send we get memberdeleted and then if we look at ourmembers array John Doe is gone he’s notthere because we used filter to filterthe idea of one out all right so we havea crud API where we can create readupdate and delete so now I want to moveon to rendering templates using atemplate engine and there’s a lot ofdifferent template engines that you canuse we’re gonna go ahead and use expresshandlebarsso if we go to the github for that weneed to install this so install Expresshandlebars and basically we can have aviews folder and we can create a mainlayout to wrap everything and then wecan create individual views and we canrender them using red start render okayso this is going to be a lot easier thanwhat we just did with the API and stuffso let’s go ahead and close up ourmembers routes and inside actually let’sinstall it first so I’m going to juststop our server let’s do an NPM installExpress – handlebars okay we’ll go aheadand run our server again and then in theindex J s I’m gonna go ahead and bringthis in let’s go right here and let’ssay Const exp so express handlebars HBSand this is in the documentation allthis stuff let’s require Expresshandlebars should be – alright now thistakes we have to add some middlewarehere so that it knows to use handlebarsso let’s go right here and just sayhandlebars middleware so first thing weneed to set the engine so app app engineand let me just show you that this is inthe documentation so I’m just doing thisright here in fact they can just copythis so we’re said setting the enginethe view engine our template engine -handlebars and then we’re just passingin this exp HBS and here we’re settingthe default layout to a file name ofmain so when we create our layout wewant to call it main dot handlebars andthen here we’re just setting the viewengine okay so we need these two linesin order to use handlebars so let’s savethat and let’s go into our folderstructure and create a folder callviews and inside views will create afolder called layouts and here’s wherewe want to create our main file so we’llsay new file main dot handlebars okaynow this is a layout that’s gonna wrapeverything so we want our doctype ourtitle all that stuff will just saymembers app and let’s just grabbootstraps so that we can make this lookdecent now for let me just explain forthe most part you’re you’re not reallygoing to do this where you have a JSONAPI and then you also have serverrendered templates it’s usually going tobe one or the other you’re usually goingto either be building an API so that youcan have react or view or something onthe front end and you’re just servingJason or you’re gonna have a completeserver-side app where you use templatessince this is a crash course I’m justtrying to show you both as well as astatic server the static folder that wedid earlier so let’s see let’s go to getbootstrap and I’m just gonna grab theCDN here and let’s go back here and justpaste that in all right so in the layoutwherever we want to output the rest ofour views with handlebars we want to usetriple curly braces and we want to putin body okay so that’s gonna output anyviews now I just want to wrap this in aclass of container just to keep it inand let’s put a class of mt4 that’smargin-top it’s just they’re justbootstrap classes and we’re gonna putbody inside therealright let’s save that so now I want tocreate a few for the index page soinside views not in layouts but just inviews I’m gonna create a file calledindex dot handlebars and for now I’mjust gonna put an h1 and we’ll just saymembersall right now if I want to render thisI’ll create a route so let’s go let’s goright here and say app because we’re notin the router anymore we’re in the mainindex so we’ll say app dot get slashbecause I want this to render on thebasically like the home page the indexpage and we just need to do res dotrender and we can pass in index becausewe want to render the index view we’lljust say homepage route all right sowe’ll save that and now if we go back toour application and reload we getmembers now the reason the static HTMLfile isn’t showing is because we havestatic down here if I were to move thisabove our homepage route and save and goback now it’s going to show that andlike I said in most cases you’re notgoing to have both like this this isit’s just because it’s a crash courseand just I want you guys to have it as areference so usually you’re not going todo something like this well I shouldn’tsay that a lot of times you might have astatic folder and you might have a formin one of the our HTML files that makesa post request whether it’s to add to adatabase or something and then you knowhave like a pose slash contact orsomething like that all right so let’ssee let’s add to our index handlebarsfile so we’re gonna have actually I wantto show you how we can pass data in sothis render will take in a secondparameter of an object and we can sendin whatever we want so let’s say liketitle and we’ll put let’s just put likemember app and then we’ll go to indexand let’s replace this now to use avariable with handlebars we just usedouble curly braces like that and we’lljust say title so now if we go back weget members app all right I’m just gonnaCenter that so let’s do class textCenter will do margin bottom three okaynow I want to also pass in the membersand list them in this template so whatwe can do is bring in our membersremember they’re in the this members j/sfile so I’ll say Const members equalslet’s do slash members so now we haveaccess to that array and I’m gonna passit into the template here so put a commawill say members and that’s all we needto do because doing this is the samething now this is an array so in ourtemplate we want to loop through it andthen output whatever we want whetherit’s just the name or the name and emailand so on so I’m gonna put in each forhere and we’re just gonna say membersand then let’s do a ul and now I want toloop through the members we passed inand to do that with handlebars we donumber sign each and then members okayand then we end it with slash each andthen in here I’m gonna put an li andlet’s just do the name so we can saythis dot name let’s also put the emailso I’ll do colon and then we’ll do thisdot email now let’s just add a bootstrapclass so we’ll say list groupand then each list item will do listgroup item all right so let’s save thatlet’s go back and reload and you can seethat it’s loading those members okay nowlast thing I want to do is create a formso that we can actually make a requestto our API to add a member from the formso I’ll just put it in the same file wecould create a whole new a whole newview for this a whole new template orwhatever but I’m just gonna put it allin here so up here let’s put a formlet’s give it a class of MB for it’sjust going to move everything down nowthe action is gonna be slash API slashmembers which we already created andthen we want to make sure that themethod of this form is a post all rightand then we’re gonna go ahead and add aform group class and then let’s do alabel we’ll say this is for name andinput with the with the class of formcontrol these are just bootstrap classesnow it’s important to have a nameattribute because that that’s what’sgonna get sent in the request body justlike when we sent Jason from postman nowwe’re sending it from a form okay that’swhy we have the URL encoded this righthere this will handle the form data soname is going to be name all right nowI’m gonna copy the form group because wealso want the email so we’re gonnachange that emaillet’s change change the type to emailthe name okay and then let’s put asubmit button so I’ll do an input withthe type of submit value we’ll just sayadd member let’s give it a bootstrapclass of BTNBTN primary and it’s due BTN block allright so go ahead and save that andlet’s reload this page here now we havea form now once I send this it’s goingto hit the sea routes API members it’sgoing to hit the post right here soit’ll create a new member it’s going toget this and this from the forum andthen down here it’s gonna add the memberand then it’s going to return Jasonwhich usually you wouldn’t do if you’redealing with templates but I’ll show youthat after so let’s go ahead and addlet’s say Kevin Smith Kevin and Gmailand send and you’ll see that it returnsJason and it includes Kevin Smith nowusually if you’re dealing with templatesyou’re gonna redirect you’re not goingto show Jason in an application likethis if you’re using server renderedviews so what you would do here I’m justgonna comment that out you would mostlikely do something like res dotredirect and then redirect to slash samepage alright so let’s go back and thenlet’s do Kevin Smith again and addmember and what happened was it addedthe member and it redirected us back toslash which is this page here and youcan see that Kevin got added ok if weadd like Matt Johnson send and nowthat’s getting added as well now I’mgonna go and just uncomment the redirector comment the redirect and uncommentthe Jason just because I want the API towork and then I’m just going to put alink in the the index page to the API soto the slash API slash members so I’lldo let’s do an a tag with the class ofBTN BTN dash lightdo margin top four and will say slashAPI slash members and let’s just sayvisit API alright so that way on thispage we have a button that will go andshow us the Jaison all right so I meanthis is kind of a weird thing to buildbut I wanted to show you guys thedifferent things you can do as far asbuilding adjacent API as well asrendering templates on the server aswell as having a static folder where youcan just add HTML files CSS and so onnow as far as authentication for themost part you’re gonna you obviouslyyou’ll have some kind of database solet’s say use MongoDB with Mongooseyou’re gonna create a user’s model witha login a register and if you’rebuilding a full stack app like let’s sayyou have view or react on the front endthen you’re probably going to deal withJSON web tokens where you pass a tokenback and forth to authenticate if you’reusing a template engine like we’re doinghere you can use passport J s in factyou can use passport with a full stackas well because if we look at strategiesthere’s a bunch of different thingsincluding JWT passport local however iswhat you would use if you’re justdealing with just Express just aserver-side app and I do have a wholeproject using passport local on YouTubeI do have some stuff with JWT as well onYouTube the best example that I can giveyou is my myrn stack course where webuild a react application we use Expresson the backend and we send JSON webtokens to authenticatewhich is it’s it’s kind of difficultit’s definitely not something I wouldget into in this crash course but justto kind of give you an idea of howauthentication works with Expressthere’s there’s no built-inauthentication is basically what I’mtrying to say so hopefully this gave yousome insight on at least you know makingrequests handling responses handlingHTTP status middleware templatesstuff like that so if you made it thislong thank you I know this is a longvideomost of these crash courses are butthat’s it so I will see you in the nextvideo hey guys one of the best if notthe best resource I can refer you to forstarting a freelance business is atstudy web development comm slashfreelancing the Creator Kyle shared itwith me and I can personally vouch thatthis bundle is well worth it you get 130page guide to freelancing and it comeswith things like invoice templatesclient proposals HTML and CSS templatesa portfolio website access to a privateFacebook community and much more so usethe code Brad 25 to get 25% off today

Article Tags:
· · ·
Article Categories:
Crash Course

Comments are closed.