Node js Course 2022 - #expressjs #mongodb with #nodejs

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

If you want to pass that Node.js Interview, here is the link: https://www.udemy.com/course/nodejs-interview-questions/

👍︎︎ 1 👤︎︎ u/Confident-Cut-7289 📅︎︎ May 09 2023 🗫︎ replies
Captions
before 2009 the javascript was only available for the browsers and every browser was competing with each other in terms of speed in terms of executing the javascript code and for that they need a javascript engine every browser has their own javascript engine but what is a javascript engine so javascript engine is a software component that execute javascript code so faster is the javascript engine faster is the browser that's why every browser has their own javascript engine just like chrome has v8 engine microsoft edge has chakra engine and firefox has spider monkey engine there are many others but these are very famous but among these the v8 engine become super fast because it was written in c plus and running or executing javascript code through c plus plus was a big win and that's why the competition among the browser makes the browser speed significantly improved and with this v8 engine something happened in 2009 a person came called rand dal and he created something called node.js and he used the same v8 engine inside this node.js but the question comes what is the node.js what he has actually created so node.js is firstly not a language it's not a framework it's a free and open source runtime for javascript now what is the runtime and how it's different from javascript engine so javascript engine just execute the code but the runtime environment just like node.js has some additional server-side modules server-side modules in node.js are like file system http operating system module and many more but the point is all these node.js thing is written in c c plus plus and javascript it's a combination of every good part of every language so that's why the node.js is extremely fast and has amazing performance now since node.js has two really great thing one is v8 engine another is additional amazing modules and that's why the node.js is able to run the javascript code onto the server and this is the breakthrough because now this is the first time node.js can run the javascript or anything can run the javascript on the server you know node.js is asynchronous in nature now what it is the what is asynchronous thing now asynchronous basically mean i don't want to wait for anything that means task b doesn't depend on task a let's have a very nice coffee analogy so you wake up and you want to have your favorite coffee just after that so how will you get the coffee you reach to the coffee machine and now there are two ways to make your coffee one is asynchronous way second is a synchronous way let's explore these things and understand what is asynchronous and what is synchronous and how it applies to node.js first let's talk about the synchronous way what is the synchronous way you pick up a cup then set your beverage and size on coffee machine you wait for the coffee to brew and dispense and be dispensed then add sugar and cream and enjoy your coffee this is synchronous thing and the key point here is this waiting time you are waiting for some task to be completed and then after you can do the next step if this is not completed you cannot do fourth and fifth step so this is synchronous let's talk about the asynchronous way same thing you can do something like this first you need to select your beverage and sizes on your coffee machine while the coffee machine is brewing the coffee you can pick up the cup add sugar and cream place it under the dispenser then coffee will be dispensed and you enjoy the coffee you can see there is no waiting time because where the first thing is taking time first task is taking time you are doing some other task you are not waiting for the task to be completed so this is called a synchronous no waiting and how this asynchronous thing applied to node.js now you know node.js works on a single thread this means you can only do one task at a time so if the client is sending a request to node.js and the server is busy doing something then another request is coming to the node.js what's going to happen is this server task is moved to the call stack and then the second request will be accepted and executed so this is the way to understand asynchronous behavior do not wait for any task if there if there is any task which is taking time move that to the call stack and what is call stack how it's going to work we will talk about that later once we understand the basics of node.js now it's the time to start with the real coding let's see how we can get the node.js in our system let's see what we are going to create at the end of this course and what is the real goal so here we have localhost 3001 the port i'm using is 3001 sent and we are having an html but what if i provide anything which is not available in our website it says page not found again an html we are sending all these html thing through express before that we are going to use just node.js to send the html but after the course will progress we will use the express and we also have a sign up route with the post request if i go it should be actually sign up with auth sign up okay and now we can see we have these data source one at bitfumes.com password is password with the post request if i send it here you can see i have created the user and now this user is having password encrypted or we are using decrypt library with this since we have this user why don't we log in our user so just go with the post request of login on the auth slash login with these two details like name like email and the password if i send you can see i'm getting this access token this is a jwt access token and we are using json web token library once again copy this and we can see we have this header bearer and then we can pass this token now what if we don't have this token and what what are the protected routes so something like book we have a full crud operation of the book so if i click here you can see we are able to get these books but if i if i am not sending this authorization token i am getting unauthorized that's great so this is for the book it's not just like this we can also create some book so we can say like we can comment these two can we do comment yeah we can do so we have that title of demo demo and author is sarthak and this is a post request for our for our slash book click on send and it should be a proper json click on send and now it says book is stored let's try to fetch all the books and at the last you can see demo book is there cool and this is for the book and we have full credit operation like update delete getting a single book with the id that's also going to work so let's try to fetch a single book like here get it and yep we have the single book detail not just these things these are obviously the major level thing we are going to use a lot of amazing package like big crypt body parser express obviously json web token mongodb mongoose nodemon and pug pug is the template engine for our uh application we are going to create multiple route file we will going to use a middleware we will going to create the user model and the book model creating the schema for these things we will create a database file where we will connect with first with mongodb only and finally with the mongoose and we will also work with the controllers this this project is not just for uh simple learning it has full thing from what is node.js to creating an authenticated crud application using node.js and express so i think this is a amazing course on the internet which is available just for you absolutely free if you like this video please give it a thumbs up which is absolutely important for me which is an encouragement for me to create more of these videos and please subscribe to this bitfumes youtube channel if you have not subscribed comment your views about this video if you like to have anything else related to node if you want anything uh update and updation on this course i will do that on my next course okay so i'm really excited for this let's start this journey to get started with node.js you first need to go and search for node and here we are so the website is nodejs.org once you go on this page that means land on this website it will ask you to download for your operating system since i'm using mac os so that's why it's asking for that now you have a two option one is the ltf lts stands for long term support and this is the latest and current version you always need to go to the lts version if you are building a production application but since we are going to learn about the node.js it's better to use the current version or latest feature so you just need to click here and save this one once this one is saved then you just need to click on it and install this once you install it you completely done with the installation open your terminal if you are on mac if you are on windows then you need to open your command prompt then if this the installation is successful then you will write node and hyphen v just this and hit enter if you are getting something like this that means you have successfully installed node in your system if you are on mac os you can also use blue install node this is also going to work and in this way you don't have to install from this node website okay so i suppose that you already have the node and node version is showing something like this then what next you just need to say note and get the help for it once you hit that then you will get the long list of some of the things node can do for you but since we are going to start with it so we can just say note and hit enter now you can see something is prop prompt up this is called r e p l so read evaluate print and loop called rapl that means here you can write some command and that's going to execute it by node.js like two plus two obviously it's four but this is just the math let's do something javascript and which is the most famous console.log and here i can say sarthak hit enter and you can see we are having two thing one is sarthak and second is undefined isn't it similar to the console we have here on our browser so open this let me zoom this for you and i'm going to say console.log sarthak and here we are getting exactly same result sarthak and undefined so what is the difference between browser javascript which is here and node.js javascript which is executed here because it seems like exactly same thing now let's talk about the difference between browser javascript and nodejavascript so the very first thing you need to understand is that browser has dom the document object model but node doesn't have it what that mean so i'm on this browser i have opened the node website and if i click on element you can see all these html you can see is considered as a term document object model but this thing is not available on our node so if i go to the terminal it's not there what's the second thing window so since we don't have any dom thing we don't have any window so if i go on the browser if i say window dot and you can see we are having long list of window object and window elements now if i open the terminal for getting into the node if i try to type window and hit enter you can see it says window is not defined it's not available in the node now the important thing is with the browser javascript you can create the interactive application now what i mean by interactive application interactive means the user can interact directly with your application so something like this if i just zoom out if i do this you can see this is actually a button and i can click on it user as a user i can interact with the javascript here but if i open the terminal there is no interaction between that because it's all running on the server end so there will be no possibility of interaction and that's why the node can create the server side apps now since the browser doesn't need any file system no file is required to run the the browser website so there is no file system file system basically means the directory structure where the code is running so code is actually executed inside of the browser so that's why they doesn't need any file system but node node code the node code wow node.js code is executed on the server end and there the code is placed on some directory and we need the directory structure we need to create the file delete the file lots of things we can do with the node and that's why node has the file system next the browser works most of the browser nowadays works on the latest es6 modules but note on the contrary doesn't support the latest version of this javascript it still uses common js what is the difference between es6 module and common js simply if you can import anything from any other my file generally you have seen in react it's like import react from react we do something like this but if you have any library obviously it's not available here so if you have any library in node so we can just say require and then we say low dash okay but this so first we can say underscore like this or we can say low dash is equal to something like this but if we want to import the low dash in the es6 we need to say import low dash from hey low dash so this one these two when we say the import word is a com is a es6 module syntax but this one is the old common js thing which is used by node.js so i think you get the point what is the difference between the node js and the browser.js we know that node.js can do a lot of things we have seen in the repl thing or we can say node.js environment here but how we can get out of this so you just need to press ctrl d to get out of it that's so easy but can we run a file or a code from a javascript file using node.js as we know node.js is useful to run or execute the javascript code that's so easy so what i'm going to do i'm going to create a file called app.js so app dot js oops where is a yeah now inside this i'm going to say console first say console.log and once again i write my name sarthak and then i press escape colon w q so you can see if i go here it's escape to get out of anything what i'm doing colon w q this is a vim command okay so if i hit enter you will now see that a file should be created which is called app.js now we need to run this app.js so we can say note app.js okay that's so easy if i hit enter you can see we have the printed out as sarthak which is so nice we can do more thing with this what next we can also do for the console of error so let's go at the end of it and i say console dot error of this is error and then if i once again press escape colon wq and run it with node you can see it's printed like this is error although we cannot differentiate right now because there is no colored scheme for this anyways let's do some magic thing now this time instead of using vim i will open this file using the vs code so i will just open this in side this vs code and now we have this app.js let's zoom this for you and now i'm going to use the for loop so i say for loop like here and i'm going to run it for let's say 10 times and every time i run i just going to log and log the index which is the actual iterated number so this should be there now instead of using this terminal i'm going to close it because now i have the integrated terminal of this vs code so i will go and click on new terminal which is here and now i just say note app.js and this should print 10 times and you can see from 0 to 9 we have this cool so that's so easy now what else we can do with this since this is running the java script but it's also running through node.js so can we do something node.js related let's do that to create a server but before that since we are starting a project let's create a github repository so i am on github creating new repository and i will say notice course 2022 and this is on the bitfumes node.js scores and it's going to be public so create and here on this first i will create a dot git ignore which is absolutely important to actually escape some file to moving into the git this is file we have it with which is extremely important and second i will create another file called read me dot md i think this should be like this read me dot md and this is not just course okay finally we have all the file let's initiate a fresh new gate repository so i'd say git init and that's created and then i will go here and use these three codes because it's already there and i just need to actually i have to first do the commit okay so get add all and then i say git commit my node course and don't worry about this this is just for me you don't have to write any code so finally it's done and then i can copy these three commands and paste it run it and remote already available anyways if i just reload this you can see my file is there cool so now let's move to the documentation to create the server you know i'm big fan of learning something from the documentation so here we are and whatever version you are using just go to the api documentation for that click on api docs and here we get the list of all the modules we have inside the nodejs now since we want to create the server and server can be created through http module let's search for it so i'm going to press ctrl f or command f to create the server to search for the http http and here we are and click on http and inside this we have a lot of functions a lot of methods are available but let's search for create server and here we are and it's given everything you need for this method but here we also have the example so first you need to import it from the node then you can just say create server and finally server dot listen let's do this so let's open the app.js and first thing as we know we need to say const and http or we can call it server they are calling http okay no server so require and we require http now you will say from where it's requiring we don't have any node module directory so since we are going to run this through node it's going to be available from the node because node environment is running this file so it will fetch from the node environment now next is you need to say const server is equal to http now since our vs code no this is from the node and if we hit dot we have the option so let's say create server there we are and now if i give the parentheses vs code is suggesting me that hey first is request listener and second is it's having the type and then whatever you want to do so we need to fetch from here which is called request and response then i will use the arrow function and then i just say response dot write writing what writing hello note okay and at the last i need to say server dot um listen listen to the port of let's say 3 000 and now i will open the integrated terminal here and run this file now you can see this is seems like it stuck but actually the server is a long running or never ending process so it's running it's waiting for something and now what we can do we can go to the server like by going to the localhost 3000 and if i hit enter you can see it's keep on running keep on running why because we have not said to our server that hey server after you write it just end it so we just need to say write dot end since we have made changes here we need to restart the server so now it's restarted run it and yes boom you can see we are having here the hello node which we have written from here we can do more thing which is given here like we can return the response as proper json and write the content so just copy this to show because this is just the beginning i'm not explaining you like everything we will do that later but for now if i see go here run it and you can see we are having a proper response of data as hello what cool so this is the first ever thing you have experienced with node.js how powerful node.js is but this is not the thing like this is not the end this is the beginning and we don't worry about the code we have written don't worry about how this is happening what this is doing what is response what is json stringify and server we're going to explain everything let's start from scratch and once again see how powerful node is before ending this i just need to say git commit with this thing and once again don't worry about this enter passphrase you don't have to do that and i will go and push it pushing to our github repository that means for every lesson or every episode you will have the code at that point when we load this http library we just said that hey require http and node will know that hey if nothing is defined then i'm going to load it from the node if node has this this is called the common js way of importing or loading any library or any package so this means that if i say here node colon hddb it's going to work similarly so if i reload this you can see it's working absolutely fine so this means if we can define it or not it doesn't matter but let's see how we can create new file and import something from there in a common js way so let's create a file called circle.js and here i'm going to say exports dot area and for now i'm going to create a function you can create a function like this or you can use the arrow function i'm going to just say i am from circle file circle dot js file okay so we need to import that circle thing from this file into our app.js now i'm going to just remove this thing by commenting it i just comment this also so that it will be available for you but not going to affect our code now i will say const area is equal to require but how we will say that circle.js so if i say circle and try to run area as a function what's going to happen if i run this node.js run node app now it says that hey i can't find module called circle why what happened but because you know whenever we say that hey require something node we will first go and check inside the node modules system now since node doesn't have any module called circle it says that hey can't find the module so how you will be loading this circle.js you need to specify that hey this is not the global or node related one it's a local file so what you need to do you need to provide the path and you just need to say dot slash here dot slash circle now when you say dot slash once this is coming inside this require node will know that hey this is something from your local it's not for for it's not from the node thing okay that's done save this file and run it again we have area but it says area is not a function so actually i need to destructure it so i just say d structure the area and if i now run it you can see i am from circle.js file okay so what does destructuring mean so if i just say like here hey this is a circle and i say circle dot and you can see now we have the area okay and we can call this function so this is going to work exactly same but we can d structure that means i can say this is going to be an object so if i just uh console console.log of circle you will see that we have a object which is having a element called area now instead of having this we can directly say that hey this is going to be some area thing inside this object which we were calling circle so just import it directly so now i can use the area great this is working fine and this is the way we can export something so what we can do we can simply say hey this function is going to accept the radius and then it's just going to return uh 2 pi r so area of circle yeah by r square actually 2 pi r is the circumference so area of circle is pi r square so i say math dot pi this is the basic javascript thing math dot pi is like 2 pi r square so r into r okay so that's great and i just need to write it like 5 if i do the 5 and i say hey give me the area with the 5 as the radius and this is the radius this is the area actually with the 5 as the radius cool so this is the way we can import the library or anything which is exported here using the common module now one more thing is like if we have one more called circumference so sir conference okay this is going to be a function once again which is accepting the radius and it's going to return 2 into math dot pi into r okay that's also going to work so i just say hey give me the circumference and give me the circumference with the radius of 5 running and we are getting both of them this is cool you can see we are repeating ourselves by saying export keyword two times what we can do actually we can create a class so i just need to say class circle and inside this i'm going to create two method first is going to have this one which is going to return me this like here and second is going to have let's have something like this so r which is going to return something like this and second function will be once again like this but it's going to return the circumference okay so this is good but let's call this function something so function circumference and function area okay and if we are defining this as a method so we don't have to define the keyword as a the function keyword so now instead of exporting if every function i can just say module dot export is and returning or exporting the circle okay like this oh i forgot the equal to sign now i have exported the module let's see what's going to happen if i just comment this and say this is going to be circle and log the circle let's see and it's a class okay so i'm going to create a const circle is equal to new off circle okay and then i say hey circle dot area and it's undefined why so we are not returning yes so once again run it and it's working so this is the way we can actually have either a full module or independent functions just like this one using the common js thing that's really great now let's talk about some global objects available in node.js for that let's go to the node let's go to the terminal first and i just go inside the repl of node and then i say global and then i press dot and then hit tab it's very important to hit tab after pressing dot no space nothing just global no space then dot no space and then hit tab not one time two times so once we have this you can see i have a full list of all the global objects available here there are a lot of things like proto value of constructor then we have array blob boolean buffer date error but the thing which i am interested to tell you is the very very important one which is the console so i just search for console here and you can see we have this console now since we have the console where it was hey sometime it's just gone yeah so global.console is there what is the meaning of this remember i told you that we can actually say console.log and something something that's good that's working absolutely fine but actually this is inside of the global object so what i'm going to do i'm going to say global dot console.log of something something with this and you can see we are getting exactly same result why so these all global objects are available on the node.js environment without importing anything without doing anything so whether i'm saying global.console.log or i'm saying console.log it's exactly same one very useful one is the process so once again if i do this and i search for process here we are this is the one dot process so similar to that we can say process we are getting this thing all the things so we can say process dot e and v and i think node in which like process dot env dot node what is that so something is okay let's have the username or home maybe what a lot of things are available in on the process so let's have and this time see what we are getting process dot env and here we have the printing work print working directory so we say dot p w d print working directory it's there and if i do the same thing global global dot process process dot env dot print working directory and like this exactly same and this is very useful because we are going to create many things where we need these long running things are up we need these objects which are available without importing without anything now there is one more important global object i'm seeing this global object and i'm smiling that means there is some catch so what i will do i will go on this file on app.js and then i will just going to say console.log off let's say underscore underscore the name it's a directory name called name if i run this one you can see i'm getting the full list of the directory where i have this project now i can also get the file name file name and that's also here with the full path and we have also seen one more thing like circle circle has this module export so seems like these things module export exports are from the global object so this means just like we do the process dot env dot print working directory if i do this you can see we are getting that so similar to this we can do for global dot process it will so if i do the global dot process dot env dot pwd then it's working so can we do the similar thing with the der name so dirt name can we do this let's see if i do this it says undefined what about file name underscore underscore file name it's still not there what about export exports still not there so what happening here seems like if i use the name directly or file name directly seems like these are the global object but it's not so to understand that let's go on the documentation and here you can see i am on the documentation and search for global module and here we are you can go here and scroll down and here it's given that object are available in all module these are object are available in all the module but they are appear to be global but they are not so they are not a global object or it's uh it's working like a global object but it's not from the global module we can say it's available in every module so their name file name export require module these are these five are global object but not appear to be global but they are not actually from the global package or global module they are readily available in all of the module so these are the important thing you need to learn about what are the global object with the global object and what are globally available object just like file name now let's move ahead in node.js by having any npm package into our node project but you know how we can get that we don't know but before understanding and using any npm library we need to first to have our we need to first understand how we can make our project ready to accept any external library so first thing we need to do is npm init since you already have node running you just need to check do you have the npm running properly or not it's 99.9 that you will have npm if you have the note cool now what's going to happen next this time i just say npm in it and now if i hit enter it's going to ask me some of the question to create a package.json file a package.json file which is responsible for managing all the packages we import through npm okay so it says what is your package name package name means project name consider it yes it's done version is 1.0 no description and entry point is app.js you can see we have this app.js if you want to have index.js or main.js you can change it then it says any test command no git repository we already have keywords nothing authored nothing license nothing everything is fine hit enter and that's done you can see a package.json with all our information is having here but it's not good to have it's very boring to have lots of yes so what i can do i can just remove this and i can just say npm in it with a y flag when i say why that means for every question you ask i'm saying yes so if i hit enter you can see exactly similar thing is happened and we have the package.json file right here right now okay so this file is there and now you can see it's saying that main the entry point is app dot js that's really cool now how we can use this package audition there are two ways one we can load the dependencies second we can run the script so one is having a test script we don't want this so we just want to have npm run dev so here inside the dev what i'm going to do i'm going to run this command node app.js that's it now instead of having node app.js here on my console i'm just going to say npm run dev which is easy for me now if i run it you can see it says hey i have this one and it's running for the app.js it's running on the main not running the script that's not good or actually yeah so now you can see it's running properly and in my app.js i just have this console log what i'm going to do i'm going to to just remove these things and uncomment this server thing and then run the server and you can see the server is really running and i can go and reload yes it is there that's how we can have our package.json and run run script or a dev script okay so that's done but you know what's happening here whenever we want to change something so suppose i just want to console log so i say log or what are the things we have on the console let's see we have do we have the message no console time console um success console log off and here i say that here i say server is running at at how i can do that i can say https colon colon not s http colon golden local host colon 3000 and that's running here now i restart the server like this and yet you can see we have the server and i press command and click i open it on a new tab that's good but what if i have to change the port so what i can do i can create const port is let's say 4000 this time and here i'm going to use uh hey i'm going to use the port and also here port now whenever i do any changes in my app.js i need to restart my server that's really a pain when you want to do a lot of changes in your application although 4000 port is working but if you want to change back to 3000 we still need to restart the server that's really a pain what is a good solution for it using a npm library and that's why i have this package.json so how we can do that for that we need to go to npm.npmgs.com and search for nodemon node1 and when i search it the first result i get let's open it and it says that it will help to develop node.js based application automatically restarting the node application when there is a change in the file okay so we need to install it how we can do that here is the command npm i i for install node mon you can run this one just click here copy that and run it or you can just run by saying npm install globally what is mean by globally so now right now i can say that nodemon if i just run it it's not available now suppose i say npm install hyphen g with a g means globally and i say node mon if i run it see what's going to happen once this is done this is globally installed now if i see my package.json i can't see any node 1 but node 1 is available throughout my system so this means if i go on any terminal so if i open it i say nodemon you can see i have the bond and i can get its version also yep 2.0.919 so using this nodemon i can run my server and i can say app.js you can see it's running it's running on localhost 3000 and 3000 is working 4000 is not working when i do any change on the server you can see it's detected some changes and now it is working on 4000 you can see it's really available right here but installing some of the library globally is not a good idea but before that what i can do i can i don't want to write nodemon app.js every time i really want to get back to npm run dev so let's open the package.json in this script instead of nodem.js i can simply say hey use the nodemon run the app.js file now if i run this still it's using the node one and running this file exactly same exactly the same okay getting back to the global thing since we have installed it globally it will be available on every project but i don't want it what i really want to have the the nodemon inside this application only so that it will not affect any other application which is maybe using the older version of nodemon first i will remove the nodemon so i say uninstall globally nodemon it's removed and this means if i try to run the node 1 getting the version it says it's not available now let's install this just for my project i can use this command i can say npm install node 1 you can also say right like hyphen g for globally installation so i is just a short form for install now i'm going to install it and one thing is going to happen it's installed it's not available is still on my system but it's available on my package.json file so if i open my package.json file you can see we have a dependency our first dependency of this project which is node 1 and version is given okay this means although my nodemon is not available globally i can run npm run dev which will going to use the node one and it's running on port 4000 now question comes if i change port it's yeah doing its job the question comes where this node mon is available if it is not available globally somewhere it has to be installed it's now installed on this node modules folder so we have seen now two file one is not a file two thing one is node module directory or node module folder second is package lock dot json we will talk about this lock.json very soon but let's see where is nodemon so if i open my node modules i can see lot of dependencies i just have installed one which is called nodemon why i'm getting lot of other things because node one is still depend on some other things so if i go to the nodemon repository i can open the package.json for nodemon you can see here we have lot of dependencies for nodemon so node 1 need chalkidar nodemon neet debug so it should be available on our node modules folder so let's see yeah we have a chocodaar we have a debug and similarly chakitar may also need some other dependency so chakidar need chai as a dev dependency or maybe normal dependency it should have so it's not given here yeah so any match braces braces there any match is there so that's why we have a lot of directories inside the node module folder but we are interested in saying that hey we have the nodemon here inside our project so that's how we get the nodemon but what about this packagelock.json so packagelock.js as the name suggests it's going to lock all the versions of each and every dependency we have inside this node module so it's locking the version so that whenever you install all these dependencies once again it's not going to take time to find which version to install it will check on the lock and install it directly so so if i kill it remove the node module or i can just say rm rf node modules and node module is gone now if i say npm install you will see it's quickly going to install all these things because everything is directly coming from package.log packagelock.json5 so we have seen how we can install any external dependency and using it in our package.json how node modules comes into the picture and next since these package lock.json or maybe especially node modules directory we don't want to push it to our git repository because it's very heavy and we don't want it so that's why i have this git ignore file now here i just say hey ignore node modules directory and if i just do that it should be ignored and this means that if i see what is the status gate status you can see there is only information about three things git ignore is changed package lock and package json so if i comment this and save this and check out the status we were going to have node modules included we don't want that so let's do the status and boom so i'm going to just have it and push it cool i'm here on this app.js where we have this very nice server using the http library now what's going to happen when like when i go to slash about on localhost it is still giving me the hello world what if i go to the login page still so what happened here it's going to return this hello world for every request from the browser i don't want that so if i go on this request you can see we have this request inside this if i go and i say request dot url request has some url thing if i reload on login slash login you can see i'm getting this slash login now if i go on about it says just about and if i go on the base url it says slash only slash don't worry about this fabicon just ignore it okay so i can do the flc statement and i can say if request dot url is equal to slash then return these things like here okay i'm removing this and let's see what's going to happen so if i go yes it's reloading and doing the hello world for the base url but what happened if i go on the about and reload the page it's keep on loading because for this one we haven't tell our server that what that server has to do so what we have to do here we can say that hey if this is a about page then return that i am about pitch that's good now same it's restarted because we have nodemon and now you can see it says i am about page if i go on the hello world it says yeah it's uh if i go on the homepage it says hello world now what about the login once again server have no idea what it has to do so that means we have to say one thing like for any other we can just say else and write it down with all these things so i just say page not found page not found okay so restart it and go on the localhost 3000 slash login it should return me that so it's about is working what about login or anything actually it should return it but something happen code getting action from eslant whatever it is maybe i need to restart it sometime something happened yeah okay so page not found for any other route which is not available on our if else statement it's going to give me the page not found about is working absolutely fine and home page is also working right but you know when we have not found page we should have a 404 uh as a status code so i am doing it i don't know what happened to my vs code and that's why i have to restart it so that's why and now if i say login it is not available because it should be 404 but something bad happened and it's it has to restart it okay so now it says 404 but we can't see the status code for that we can open the insomnia so insomnia we can open and let's here we have the insomnia and now i can say on the 3000 slash login if i do a get request send it you can see we are getting the 404 but for about page we are getting 200 that's really good and this is how we handle the routing in basic http node server for our node.js application we are having this routing for about for home page and for every other page now i don't like to return this with the json file actually i want to write some data so i just say response dot right and writing page not found okay so let's run this server and once again it should be yeah it's running actually that's why it's giving error so go here and slash login is there it says page not found but i don't want to have this page not found first you can see it yes it is giving the page not found but it is still loading because we have not ended the request so once we done with that we just need to say request dot end okay so restarting it reload and uh it's not saving this what happened yeah now once again if i reload page not found but page not found should be html isn't it so i can do something like hey i want one h1 tag slash h1 tag and once again it should be having some issue with that now it's restarted reload and oh that's really bad what happened here is it actually or i can say it's it's literally printed the thing which i said it's not printed as the compiled version of html how we can do that the problem here is this content type what content type we are sending we are sending application json so that's why it's taking time now i just need to say it's a text html okay okay so now restart and this problem with my vs code reload and boom you can see we have a proper html code if i inspect it i can found all the body with html that's really nice so can we do the same thing for other yes we just need to change the content type and the content type will become text slash html and we are ending this without anything but we just need to say response dot right inside h1 tag i am about about page slash h1 and close it okay and this bad thing happening to my vs code and i can do the same for this text html change it like here response dot right writing with the h1 tag welcome to node.js scores closing the h1 tag done so it has to be restarted finally that's done go to the about page i'm about page go to the home page and it says welcome to node.js course that's good but you know what's happening here is something bad happening but we know it's crashing we will tackle that later but every time we need to write the html as a string it's not good for us so what we can do we can create some pages here and then we serve these html from that pages how we can do that let's create a directory called template or we can call it page i call it page so it's creating maybe i need to restart the vs code it's oops restart reload actually reload reload window okay once again create the page yeah it's done and now i'm going to say home dot html and here i will cut this from here and paste it like this okay that seems like a good idea and server is running now how we can return a file so file is inside the page slash home home dot html now if i do this what's going to happen let's see it's literally printed out the home slash page slash home.html one thing is that how we need to tell to our nodejs that we want to return a html file so basically we need to first read the html file the content of this html file and then send that here that's really challenge no worries because we are going to understand about the file system library or file system in node.js we want to serve this file by reading this file the file content the html we have inside this and then display it here for that we first need to read the file and for reading purpose we will go on the documentation search for file system which is here and then we need to read the file how we can read it so let's search for read file and there are many date files so there are fs promise we don't want we just want the fs one so click here on the read file and here we get the code so you can see it says that you just need to import read file from file system and in this case we will use the common js the requirement not the import one and then we can say read file and the file name and some callback okay let's try this one so here we are and we are getting some kind of error and we want to handle it it's crashing our application and say it says that right after end so you are trying to write after you have sent the end part so we just remove this end from these places and only provide the end after everything is done okay now first we need to have the file system and we say require fs the file system you can also say node file system and that's going to work but let's have this one only okay now inside this route the url of base url i just need to say fs dot read file and after that we need to provide the file path which is this one okay so file path and then we have some callback in this callback you can see we get first the error and second whatever the data i have okay so first we get the error so err and then the data so we need to handle the error it's very important so if there is some error then throw that error so let's have this like here and that's cool but after that we need to write the data we need to write the header or we can write the header directly before it and then we can say hey this is going to be the writing of the data okay that's very nice let's go on localhost 3000 reload this page and boom you can see we have the page content and it says that page not found but we don't want that because on our home.html we said welcome to node.js what happened here so we are on base url but still we are getting this page not found so what's what we are going to do uh we need to just log this error see if there is any error or not reload and now it says there is no error so what about the data so if i reload and now we have the data so we have the data but this data is in some different format we need to have the actual content which is this one as a text so how we can tell our file system that hey file system use some different coding scheme so here we should get something and it says that uh if option is a string then it then it is specify the encoding so what kind of encoding we want the second parameter we just need to define that it should be the udf8 okay that's good so this means here i just need to say utf-8 this one now after doing that if i go reload the page and yeah we are getting this welcome to node.js with the h1 tag now since we are getting this we should be able to see this response dot right but it is still giving me the page not found why because maybe i need to say else if and finally the else part okay now reload and it's not doing anything it's having blank page what happened here you can see we are not getting anything even we are not getting any uh yes any error so something is not good here maybe we can try to end it right here at this point oh that's good welcome to node.js course so we are ending this here and i believe we need to end it as soon as possible inside of this file system okay so that's okay if we can end it here and now since we have if else it will go only on one place at a time so it will not give that previous kind of error so yeah it's welcome to node.js similar to that we need to do for the about page so copy that and instead of this end and write i just paste it and i say hey this is going to be the about page and let's copy and paste it for about page and here it says i am about page okay and this should work on the about page also slash about yeah it's working on the about page and finally 404 so let's say 404.html and this just say page not found three dot okay and at last we just need to say hey these things will work like this and 404 page and if i say login yeah page not found you know with file system it's not just we can read file we can also write on the file so how do we do that let's search for write file and we get it here let's go here and we get the code it's very easy you just need to say right file the file name the data and the callback cool let's do that but for that i will create a new endpoint and i will call this create file so create hyphen file and here instead of read file i will say write file and writing file on a directory called temp directory so i will say temp slash test dot dot html okay and here i need to provide some data so just like that i will say h1 tag h1 and i say this is a test file okay now if there is any error we can throw that error otherwise we just write the content okay that's very very nice and finally we can say like what is the data data is file is created okay that's done very very easy so let's see what's going to happen create file and it's not working what happened let's open the console and see what's going to happen it first say hey there is no such directory or file called test yeah there is no directory so let's create it so i'm going to create called temp directory and now i will save this file once again to restart the server because of the nodemon and now if i reload this you can see it says file is created that means the file should be available on the temp test.html boom that's there wow that's so easy but now what i will do i will move this in a constant called data and then use that data like this and it's also going to work so once again reload and you will see that it's still here but you know i have actually do did that two times so it should be like having two times no when you say right that means it will going to write something inside this so if i say updated content reload this page what do you think is this going to be the updated text or the previous text let's see here you can see it's updated one that means write file will put all the data replace it with the previous content if we have how do we actually append it so when i say append the data so instead of write file you just need to say append file now as soon as you reload many times as many time you are reloading that many time you will see that text coming here okay that's so nice we have done that and now uh what i will do i will do some crazy stuff i will just go and use the for loop and for loop will going to run for 100 times okay once uh yeah 100 000 times and for every 100 000 iterations i will do this thing and obviously we don't want to write the content so what i will do i will just move this out of here okay so let's go reload it something happened check server server is crashed it says too many file open because it's not completing the task every time you open the file but you can see this page is having a lot of time that html if i save it you can see it formatted and boom it's having almost 61 000 times so it's not running for full 100 000 it's it ran for 61 000 times something so because of the file opening thing anyways we have 61 000 times running so let's try this one more time if i reload it should be crashed yes it is crashed but once again it should have the data on our file with the content of 122 000 now this file become very big so if i reveal this in finder and try to find it it's a 3.3 mb of file we can also do that with some magic of once again reloading and to make server re-running one more time reload and it should be now having too many content like 6.5 mb data okay so what i'm going to do i'm going to do some again crazy stuff i am going to create another endpoint or maybe on the about page instead of about page let's let's serve the temp slash test.html let's see what's going to happen when i go on the slash about page hit enter you can see it's keep loading and loading and my my browser is almost crashed but it's not that crashed so let's see what we have next in nodejs so now let's talk about the event loop what is event loop and why we need it but before that we know that node.js can be asynchronous in nature and have non-blocking io input output it doesn't wait for any function to complete it it's a killer feature of node.js which made it that successful but we also know that node.js runs on single thread and there is one thing happening at a time if only one thing happening at a time that's a limitation but node converted that limitation into a helpful feature how using the event loop system and the call stack system so what is event two event loop basically means continuously checking the call stack to see if there is any function now question comes what is call stack and what it is doing so think about a loop in node.js which is constantly running and checking somewhere called call stack for any function to be executed so let's go and understand that with a example now suppose we have this kind of example which is having three functions funcs func one func two and func 3 and let's see how we can call it for that let's go to the vs code and here i'm going to create that so first const func 1 is going to console log func one okay similarly we have the funct2 which is logging func 2 and func 3 is going to yes log func three but then it will also call func two and func one so first it's calling func one and then func two and to run this execute this i'm going to finally call func 3. now what's going to happen here let's get back to the slides and understand it here we have func 3 so first what's going to happen phone 3 will going to run then it will go inside this function it will execute the console log for func 3 and then calling func 1 which is going to uh log func 1 and then calling func 2 which is going to log func 2. it's confusing yes let's understand it deeply so there's a call stack whenever node c any function move that to a call stack or a collection of function to be executed so first it's going to run func three okay phone three is there now what's going to happen after that after that font three will first go into log the func three not fun it's just funk three so it will execute this code now func three is still running but after that that will be done and it will go inside of the func one here okay so move it here like this okay then what's going to happen in the func one inside the func one it's going to console log func one that means on the caller stack another log comes which is called func one so that will go like here now after that what's going to happen this is going to be done the funk one console log is done so it will be removed from the call stack but still we are on func one it will check for anything else on the func one okay it's not anything is not there then it will complete the func one so function one is completed now what's going to happen next once the function one is completed we are still on function three function three is still running so it will check okay this is done this is done what next funk 2 now it will go on the func 2 that means funk 2 will come on the call stack now it need to execute func 2 so it will go inside of the funct 2 which is going to log this thing that means now on the caller stack func 2 log come once this is completed then it will check for any other thing on the func 2. it says that okay nothing is there and then it will get back to func 3. now it will again check on the funct 3 is there anything left to run it says oh nothing so i need to complete the funk 3. so let's see what's going to happen let's open the console and you can see func 3 1 and 2. this is the call stack so this is fine but let's do something great i'm going to put this funk one in a timeout okay and this time out is a zero second timeout that means it's not going to wait for any second just execute this one now what do you think what should be the console log sequence so one thing more we can also directly call this func one since this is this need the function so yes we are giving it now this will become easy so in our previous experience from our previous experience first it will console log func 3 because it's there then it will go inside the timeout and timeout is a function and then it says okay we need to go inside the funk one funk one is logging the console log so it should be giving func one and after that it should give us func two this should be the sequence which is from our previous experience but let's open the console log and see this is not happening first we are getting func three that's okay then we are getting funk 2 which is not good then we are getting server is running which is absolutely not good and finally at the last we are getting funk 1 which is inside the set timeout so what's happening here now what happening here is the set timeout is a time ticking process although this is having 0 millisecond but node will know that this will take some time so it will move this on the call stack and then it will say that okay i will execute it at the last once everything is done every instant thing is done i will execute this set timeout at the last and then i will check for the timeout like when i need to execute this but the sequence will be first func 3 set timeout keep it aside keep it on the call stack and we'll take it take care of it later then it will execute functo then it will go at the last it will say okay there is a console log if once everything is done it says oh there is a time for set timeout let's see what is the timeout then it says okay zero second print it cool so that's why we are getting func 3 2 server is running and the func one okay that's done one thing more we can do what if we have a new promise and this promise will going to have resolve and reject thing then i will say resolve i am a promise and i say dot then once this is this promise is resolved then console log the response we are getting okay now this should be a arrow function what should be the sequence once again we know that this timeout will be executed at the last we don't know about this promise so it will be like funk 3 then this will be executed at the last don't know about the funk 2 so maybe this could be the second one and third is funk two and fourth one will be funk one is this going to be the sequence let's see so this is the sequence but what we are getting we are getting funk 3 but funk 2 server is running i am promise and function 1. so now something great is happening which is like this promise is also moved apart and moved to the call stack and it says that okay this is also a time consuming process i will take care of it later once everything is done everything means every instant thing is done so that's why it says that okay this is the promise i will execute it and let's save it yeah executed and after that it says that there's a set timeout but why not first running the promise and then running the timeout what if i change the sequence like here you can see still promise is running first and timeout is running after that we need to understand what is the sequence what is the priority for node.js now we don't know why the node.js is executing set timeout at the last and what is the priority list for the event loop to run different different time consuming tasks like set timeout and promise before understanding that i want to let you know about one more important thing which is called process dot next tick now what is this next tick mean so i will just log and i say i am next take okay so basically process dot next tick says that once everything is cleared from the call stack that means every thing is done run this function or run this callback which is inside this next tick now what's going to happen if i just to remove these two i don't want this and i just want to run the funk one so what should be the sequence func three func one func two server is running and at the last it should give us the i am next stick okay three one two server is running and am the next stick why because after this there is nothing to execute call stack will be cleared now next thing let's get back our set timeout and the promises now what should be the sequence where this next stick will come where the set timeout log will come and where the promise log will come for that let's open once again the console and there is some magic happening from 3 funk 2 is good from 3 funk 2 is good then server is running is good and then since the call stack will become empty for the instant instant functions it will say that okay the the there is a time for next tick so next stick is coming and after that it will resolve the promise and finally it will resolve the set timeout so this is the real sequence let me write the sequence for you so sequence for execution is first it's going to execute the mini task and mini task is the word i'm giving and this is for the next tick so from this event loop it will check for events and it says that okay i need to execute these three time consuming things and first one is the next tick which is the mini task then comes the micro task micro tasks are like promises promises okay so then it will execute the promises and after that it will execute the macro task macro task macro task like set timeout or maybe set interval something like that okay so this is the sequence or the priority list for the node.js to execute the functions using the event loop from the call stack and i think you get the point if you're not getting that point i highly recommend you to go to nodejs.dev website and understand each and everything from this learn and you can learn various other things also that's great and let's understand more thing in node.js we can do more things with the modules we have on the node.js but you know just to return a html file like this we have to code a lot so if i go to app.js and i remove all these things which is just for understanding call stack you can see we need to do a lot of thing just to return or print the html content from this html file it's yes a core node.js thing but time consuming for making things easy we need to migrate to the framework of node.js which is called express js it's absolutely important to understand express js because 90 percent of the time you will going to use 95 percent of the time you are going to use the express js okay so this is the website of express.js you can check out the version currently five version is in beta but we need to have this in our node project so right now our node project structure something like this on our package.json we just have the nodemon as the dependency but we also want the express to be here how it's going to be available first we need to run this function this command npm install express and save is just an optional thing which is going to have this here inside the dependency so i just say here npm install express okay now hit enter and this is installed wow that's so light you can see the version is given here on the express and we are done with that how do we get it started with express.js so we need to go to the getting started part and we have the installation which we have done on our page now we need to go to the hello world it's absolutely important to follow the documentation for anything i highly recommend to follow documentation every time you do anything first you need to get the express then you need to create the app by just calling the express and then you can get started with this like here okay seems like so easy stuff let's go here go to the app.js and now i'm not going to remove everything what i will do i will actually call main.js and do the express thing here so it's going to be express and i say require express and you can see since i have installed it my vs code is giving suggestion then i need to create the app so app is equal to express that's done finally i need to say app dot listen and listening to some callback and here we can just say console log server is listening server is running at i can just create a constant of port is 3000 and i say put okay is this going to work you can see we can also get the port directly from here that's not a big deal we need to first define the port actually so we need to define the port here so first one is the port so we can say port and cool now i need to stop this one and let's start this express one at localhost 5000 to see the difference npm run dev but it is still running the 3000 why remember we said that we need to run app.js when we go on the package.json the dev command is saying nodemon run app.js we don't want that we want the main.js to be ran now i will kill this server once again run the npm run in dev and this time it says 5000 is in use previously we faced same issue so let's use 3001 actually and i will also say here http colon slash local host colon 3001 okay so it should be available at 3001 and now it says cannot have any get here okay so what we are doing wrong we are running the server but we don't have any endpoint how we do the endpoint thing go to the express and it says you just need to say app.get define the endpoint do the response so easy we can see we don't have to do any response dot and response dot right app.get on slash and here we will see request response and i should do something like this and here i just need to say response dot send hello world and that's it that's the only thing we need to do to have our first ever hello world with the expresses okay so that's seems like so easy stuff let's do and do some other things with the express when we use the express js express is actually built over node.js this means that if somehow sometime we need to execute the basic node.js code then yes we can do that and i'm going to explain with a new concept of event emitter so let's go to the documentation of node and search for event and if you go on the left side yeah we have this event and here you can see we can emit an event and we can listen for the event so what is event and something is going to happen and then we can raise an event and that event can be listened by node.js from anywhere so what's going to happen how it's going to work let's see first i will go and say const event no not event what's that events events okay and from here i just get the event emitter okay so we can just change it to common js event emitter will be there like this then i say const new event my event is new event emitter so my event is equal to new event emitter and now i say my event dot and i can have the on that means whenever any event is raised or emitted and here first we need to give the event name event name is test event and what's going to happen on that the listener so it's going to be a function and here you can see if we can do anything so here i just say log and this event is listening okay how we can emit the event so this is the event my event is there whenever we go on any route we can say my event dot emit and emitting the same event name which is test event and that's good so whenever we visit this route we should have a console log on our terminal here so let's go here and open this 3001 run it no issue but here you can see this event is listening and this will be useful when you want to do anything like a database transaction so suppose you want to store something and whenever you store you want to emit that something is stored then anywhere on your application you can listen for that event and do something if you really want to do next you can do one more thing whenever you are emitting any event you can send some data so suppose i want to send my name so sarthak is here this data will be available on this callback so this callback will get you the data whatever you are passing so i'm just going to log this data also so let's see i just clear the log go to the server reload it it says is not defined okay yes we need to provide it as a string not any variable so yes there is no error and now you can see after this this is this event is listening we have the name as sarthak the data whatever we are providing here will be available here okay so this is how you can understand the events and you get that yes even though we are using the express js we can also combine the node concept the basic node concept inside this express js and express is actually built over the node.js and that's the reason we will be able to do that now let's continue with the express and see more of the routing thing and move forward in the journey of nodejs to understand more about the express routing go to the getting started part and click on a basic routing when we go here it says that you just use the method name here and the path and the handler this means we are just using the get request what if we want to have a post request let's try that it says on the post request for the same home page that means the base url what we want to do we just want to send a json data and will be which will be like data is hello world from post method okay but how do we test this we need to use the insomnia here we have the insomnia and localhost 3000 on the get request you can see uh it's actually not three thousand it's three thousand one send it and yes we are getting hello world but what if i do the same with the post request you can see we are getting the data hello world from post method because we are sending a json request not sending a simple text this kind of structure sending a json uh json data is useful when creating any api thing okay so that's not the end yet you can go on the header you can see it has converted the application json as the content type which is absolutely useful when we create any api or when we send the json just like this you can also do any post or patch or maybe delete request anything you want to do you can do right here from our app dot and something method so this is good for the base url what if i try to see slash about page now it says cannot get slash about this is not a good response and how do we handle it i just want to say that for any other route so i say all so first handle this one if these two doesn't match then check on the all thing and all for slash and then asterisk that means after slash anything come will go here and what i will do here i will just say response dot send page not found okay let's try this and run it it says response is not available yeah obviously request comma response and reload page not found for any other thing but if i go on the base url hello world is there that's so easy to write all these things and remember once again go to the app.js and remember all these ugly code we need to write just to handle all the routes and throw the html pages okay now what if i want to create a route which will have some kind of parameter or a dynamic routing so i'm going to create a dynamic route called slash book so first we have this book route which is going to return all books okay but i will also create one more route which is going to be slash book slash and the book title or maybe id so for now i just have the id and i say single book now let's try these two and see how we can get this id from the url so right now if i go on the slash book you can see it says all book but if i say slash book slash 34 how we can get that 34 because we need to fetch the data from the database maybe in the future for that what we have to do this id is actually inside the request so first we log the request and go reload and we will see that here we have route we have path and we should also have somewhere parents so maybe i can search for params and yeah we can see we have this params so i say request dot params like this that means if i now reload reload yeah id 34 is there so yes we can say single book of id colon of request dot params so like here now anything which is coming from the client side from the user or anything which is coming from the request will be inside this request object and anything we return or we do the response go in the response response object that's the simple concept so this is how we can get the id oops params.id like this okay so yeah it will become it will become 34 right here right now so what i'm going to do i'm going to just convert this to slash book and move it right here because these two will this one actually going to create the book this one is for fetching the book so i will say that book is stored this is just the fake thing i'm doing but you can see these two routes are almost similar so we can do some more magic here i can actually do app dot route for slash book and then i can chain all these functions like get function and the post function so i say get and you can see we are getting it so instead of doing that i can just do like this and like this okay so app for the route of slash book i just need to say slash and slash why because we have already defined that whatever we chain is going to be prefixed with the book it's like a route group but since we know that this is going to be the book only so i can just remove this because it says that hey this is the actual route so why you are defining it that's cool so now if i go on slash book you can see still we are having all books and go to the post request on slash book send it it says book is stored yeah this means this one is working absolutely fine but as we grow with our application you can see a lot of routes are available here and all the routes are just actually filling up this file and it's not a good practice so i want to extract all these route from this file and move it into a dedicated file called router so i will say routes router or routes routes slash maybe i can say index dot js like this so inside this index.js i need to move all these routes so i can cut all these route and paste it here okay so we have pasted but can we just import it like const routes is equal to require of same library for the route slash index is this going to work i'm not sure let's try first you can see this app is crashed it says app is not defined inside your the routes file because when i go on the route file the index file you can see we are using the app how do we get the app so actually we need to change from app to a router so i say const router is equal to express and this means we need the express first so let's say const express is equal to require express now instead of creating an app like this we are doing here like here we can just say express dot router like this okay and now whenever we are using app just replace that with our router okay so this is done is this going to work let's see okay so there is no error can we do that reload it says no it's not available so what's going to happen here we have all the routes but we are just importing route we are not telling this express application that hey application here are all the routes so what we have to do we need to say app dot use of these routes when i say use that means it's going to include all these things inside this express application so once again it's crashed now what's the issue it says require a middleware function so basically what happening let's just console log this route log routes and i just comment this one and see is there anything reload and you can see this is empty why because in our index file where we have the routes we are not exporting anything remember the module dot exports thing and yes we need to export our router and once we export it then you can see all the route is there this means now i can remove the console log and i will tell to our express that hey express use all these routes so amazing now if i go reload the page yes all books are there and every route is working perfectly fine so this is the way you can handle the route you can understand about the route and extract the route now one more thing is there you can see some of the routes are only related to our book so what we can do we can say hey there is a book dot gs route and then i will do the same thing here but just for the book related route so book related these routes these three route and all other route i need to remove so here we have the book route so i can call this router as my book router okay so we have exported this book router now inside this index.js and remove all the route related to book then what next we have to actually combine all these routers so then i say router dot use this router is using another router which is going to the book router and i need to import it so i say book router required on slash book okay is this going to work let's now see first we have this go here reload it's not working the homepage is working but flashbook is not working why is that because you can see first we are accessing this one then we are checking for this one and it says that okay anything i'm going to accept and return the response which is page not found and then after it will check so if this is going to match it will never go into the express will never going to check about this route so first let's comment this and see is this going to work or not reload and yeah it's working this is working that means what we can do we can just move this route here and that's the simple solution so first check for this route check for all these route if nothing matches then say that okay page not found okay so yes it is working and if i say anything it says page not found so this is all about the app routes and how we can extract the route for a different different type of route and have it so you can also do something like this or you can define any specific routing then also it's going to work the one thing is there if you go on the index you can see i'm just saying book route we can also define it like here say slash book is going to use this book route and then if i go here i just remove this slash book and slash book from here and this will be ensuring that before every route we create inside the book router will prefixed with the slash book okay so that's going to work absolutely fine if i say 34 yet it's working okay so remember if you want to use it like this prefixing any route that's also going to work if you don't want that's up to you cool so we have seen a lot of things in the routing and let's move to the next thing in express inside node.js remember when we were having just node then we were actually returning the html file let's work on this let's return an html file in express so i'm on the index routes here i have the base route the home route instead of sending a simple text i can say send file and now the file is actually page slash home dot html which is inside this page home dot html that's good let's see if this is working or not reload and now it says path must be absolute or specify root to send file this should be absolute absolute means we first need to go through the process of learning what is der name that means directory name and for now i just say return sending anything to see what we are having here so reload yes that's okay but you can see it's having the base url till the routes directory the routes directive by because this function is running inside this routes index.html that's why it's given here so what if i just say like send file but before that just add directory name then add this text here but go one step one step up let's see is this going to work no it's not working because i need to comment this one also okay now this time it says forbidden so what actually happened so we need to create an absolute path and this is not an absolute path thing how it's going to work for that we need to use a path module of node so first let's say const path is equal to require path okay now what if i say path dot join off underscore underscore directory and some text what's going to happen let's see so i'm here clean up refresh also say yeah it's saying forbidden but at the top you can see we have exactly the route given till this thing okay now so if this is the absolute path we can cut it from here and paste it with this thing so let's have the path dot join the name plus this full path of our html file reload and yeah you can see welcome to node.js course yeah this is working absolutely fine so great so to see that yes we are able to complete this now simple similar to this we can actually run this for 404 also like here so if we say anything here it says page not found which is our html page that's so that's nice and this is how we can serve any html page using the express.js next what we need here we actually need to have some template engine now what is template engine here what if i send some data how we can send some data here inside any html file so suppose i want to say that hey welcome to whatever it is but then i say welcome and then i want to have a name variable which will be print my name when i execute this so it should be welcome sarthak okay how we can do that we need to pass the field like hey i'm going to pass name here name is going to be the sarthak okay is this going to work no it's not working how do we do that now we need to work with some amazing thing you know sending a file html file is good but we can also use one more function called render and when we do the render thing let's see what's going to happen if i reload it says can't find module html actually we need to remove this html and then if i reload this page it says no default engine was the specify and no extension what was provided so what is engine it's talking about that template engine so here if you go on the guide and using template engine here it's given for the express js now what we can do we can just say npm install pug and save so just install this and save it while this is saving or installing we just need to set or define the view engine and this is the view engine it's talking about here so let's copy this one and go on and go to the main.js and after this routes we have we are defining the bug then we need to say i need to render something but from where from where it's going to render yeah we are defining all the path here that's good is this going to work let's reload now it says fail to look view it says view for the html file inside node.js page home how it's working it says that it's not able to find any view inside this home has at this home is actually an html file serve this file but if i do that it says can't find module what happening here actually whenever you use any template engine every template engine has their own extension so for the pug we need to have a pug and that should be inside the views directory by default okay so i will create a views directory so first create a views directory inside this views directory i'm going to create a index dot pug p-u-g that's extremely important and what should be the structure it should be like html head and like here so it's going to use some different kind of structure like a yaml thing so title is the title message is the message but for now i just say message is hello world title is my title you can see i'm writing as a variable or a string thing here and plus i'm having the structure of html also so if i do this i just need to say one thing which is the view name and my name is index means my view name is index now if i reload you can see hello world is there and title is my title that's how this is going to work but remember we want to show this dynamically that means we need to send this name from here and show it here remember we can have the name so i need to just say welcome welcome to this node course and then i use h2 and i say welcome and then sarthak so it should be like here welcome and name cool let's try yeah you can see it's actually rendering whatever we are sending from this render function inside our view you can get the data from the database and send it here like this that's so easy and so nice to work with the template engines but you need to be familiar with this kind of syntax in the pug if you have if you are using this bug okay that's really good we have seen how we can work with the views let's move forward now let's work on the rest api for the books now how do we do that first is to create a rest api we need the end points so if i go on the routes for book we have a get route for all the book post route to create all create a book then we need one route to get a book which is this one we need one more route to update uh update our book which is going to be have same and we can actually have last one for delete so you can see these two routes are exactly similar so single book of id to update to delete okay so just like we are using here combining these two so we can do the same thing here so we say dot route for slash of id and we don't need these two and then let's combine it like here okay so we have combined these two route we have combined these two route and i think we need to combine this one also so that should be like here and yeah so like this that's done we have done this thing but you know what we are doing here is just the end point we need to connect to the database first so how do we do that let's go to the documentation go on the express on the api on the guides at the last we have database integration click there and we are here and we are going to use the mongodb so click on that and it need to to us it need for this db driver or package so let's install this one here on our application so this is installing mongodb now while this is installing how do we configure mongodb it says that for the version 3 and first check which version we are having here so go to the package.json go to the dependency and it says mongodb version 4 okay we have fourth version so obviously it's greater than third one so we can just look at here um if you are not if you don't want to use these example just go to this link which will open that the driver github repository and there is one more place here we can say mongodb search for this one and here we are let's see how we can do that so this page and the github page is exactly same i like to have something from here so it says that once you have this then you can require the mongodb client like this you can set up something like this define the database name and start working okay so these three four lines are very important so what i'm going to do i'm going to first create a database directory and inside this i will create db.js inside that i paste it now it's including the client then it says what is the url in localhost this is the exact url and then we create the client using this url and we need to define the database name so what is the database name we are going to use we are going to use node.js course database name i will use underscore and now how do we connect so if you don't have the mongodb you can install the mongodb so i say mongodb install and if you are a visual learner then you need to install the mongodb atlas or if you want to install the cli version then everything is here so it says that if you are on mac you need to install the xcode and then with the brew you can install the mongodb i already have the mongodb so i can just use mongoose in my local environment which is you can see is having the exact same url which we want and then here we can play with that so first let's see how many databases we have so i just need to say show dbs and hit enter you can see we are having these dbs their database now the good part of db is that once you start creating something it will be available here so we don't have to create any database like right now because we just define it here and it will going to work everything is good you can see we are defining database we are defining but what next we need to go once again on the npm and then it says you need to save first client.connect and once it is connected then you can say db client.db and the name and then interacting with the dbs okay so here we just need to say client dot connect but this is a a wait process yes so we need to say await we will tackle it later and then we need to connect to the db so connect to the db that's good everything is good but this away it should be uh in a function so we can say connect and this should be a sync function and move these two here and at last return the db we need to make sure this is also an await process and finally we have to say export module dot exports is equal to connect function okay so we have done with this what happened anyways okay so this is done and we can go here on the books route and here we can just import our connect method which is just by doing the require inside of the database and db then wherever we want to do something we can do that okay so how do we do that how do we create a new something inside our node.js scores db although that db is not available inside our list of dbs because once we start interacting it it will be created okay so that means we need to first go on this npm and here you see it should be available for create or insert so here we have create index but we don't want the create index we just want the normal indexing insert many so here we have insert many or we can just have the insert so let's go to our vs code and here we are importing the connect method and now let's create the db and using the await and just do the connect since we are using await we need to use the async and once we have the db then we can start creating so we don't want to create here we want to create on the post request and i'm keeping this here because later on we will need it so maybe i can comment it okay so here i just need to say db dot collection and which collection collection of book think about collection as the table name so then i just need to say insert one and the data we want to have is something like this data is equal to title is power of consistency and let's say author is unknown okay now we know that we don't have the database we don't have the collection because we have never created anything but that is a good part of mongodb once you start interacting with any collection or any database it will be created on the fly so once you do this then let's see what's going to happen and make sure this is also an await so it will wait for this to complete and then return our response how do we check that we need to open the insomnia so on this insomnia we are having this book and now what i will do i will just click on send it says can't connect to server there is some issue on the server and server says something bad happen okay oh yeah when we use the route we don't need to provide any path so it's just a get request on this route okay now this is done everything is fine let's go to the insomnia click on send you can see it says book is stored yeah really book is really stored how we can check first we can check from terminal and here in the terminal we first say use our collection but first let's see do we really have the database or not so db uh show dbs and yeah now we have this db node js scores so i will use this node.js course db you can see now i switched to this database then i just need to say here that show me all the collections i have and i only have one collection called book so i say db which is which is referring to the current db which is node.js course dot book which is the collection name dot find and when i'm not giving any id then it will give me everything like this so you can see this is here and it's inside the array every object is there with the proper id and this id is given by mongodb we don't have to worry about it cool since we have this now it's time to get all the books we have on our database so that's why i have this commented out so here i need to say const books is equal to await db dot collection which collection book collection and dot find and when i'm not giving anything it will find me everything and instead of send i just say request or response dot json and returning all the books let's now see this one so on the same route we put the get request and click on send it says something something event and events count so i think i need to do dot to array so it will convert collection to the array and now you can see we have this book wow that's so so great we have done the database connection we have done we have created a new book and we are getting all the books that's so great next what we want we don't want to hard code this book we want to get something from the user like we are sending the email and the password just like that we need to send the title and the author and that information we will store into the database now we need to store the information for the new book from our request and now the question comes how we can get the form data or the data we are sending from our form into this request how we can get that for that actually we need to get another npm package which is called body parser so if i run it you can see we are getting a lot of body parser but let's see which one we need to use we need to use this one okay so we have body parser json error so we can just require the body parts or maybe i can use the body parser like this yeah this one is okay so we need to install it so click on it and then run it it is installed that's so quick then how we can use it once we have that we just need to get it require it and then use it on our express so yeah so app.use like means access dot use body parser encoded extended false so something extended false it says bars application json for that and we need this one for now so let's do that for that we need to go to the main.js where we have our express and then we need to require const body parser is equal to require body parser and then i can say there is use thing so app.use and using this body parser.json okay so this is the one then how we can get that the body you just need to say request dot body thing like it here okay so let's check this if this is working or not we have it go to our books route and here we can simply log request dot and then i will do the body and you can see now we have the body in this and we are getting it for now i just to comment these things otherwise it will create another one so response dot json is request dot body and let's have it on the console also so here we have the console cleared click on send and you can see whatever we are sending we are getting it back that's great so we have it now what we just need to do we can uncomment all these things and instead of this data we need to say request dot body okay that's so great we are done with this and now we need the title title is uh clean code and author is uh uncle bob uncle bob okay let's click on sent and it says book is created how we can verify we already have the route for all the books let's go here and go to slash book and yes we have done with this so this is for our request and body parser which is extremely important to get it easily from our request collection now let's work on all other routes we have like patch delete and getting the single book okay so first we need to fetch this book id so we know it will be from request param so i say const id is equal to request.params.id okay then we need the db collection or db connection actually like here and then we say const book is equal to db dot collection of book dot find with our id cool and at last we need to return this so request.json and give me the book okay so how this is going to work let's go we have this id copy that id go to the book and server is not running oh really something bad happened okay so it says await you're using a weight and you have to define a sync that's how it's going to work okay so i say slash and after slash we can say this is the id let's see if i hit enter okay i think i need to do 2 array dot 2 array and run it once again we have some issue what's that query filter must be plain object or object id to test this let's go to the terminal and here i am on the node.js course database and i say db.book collection dot find me everything so you can see actually when we do the find we need to say underscore id is the object id and then provide the id not directly like this so there are two things here important which is object id and underscore id okay get back and here first make sure this is underscore id and then we provide it like object id and it should be coming from mongodb and providing the id and make sure this is again a await process and go reload and yeah we have this one okay we can do one more thing like we can just copy or cut this from here paste it here and directly pass like this and now make this id as underscore id so we don't have to provide that here and it seemed like a good refactoring one more time it's working let's try with the first one and this is also working okay so we saw how we can get a single id it's now time to update something once again we need to get these two things working and then second we also need the we also need the request body okay and we need the request body on the update part so first we can say db dot collection of book dot find okay but after the finding with the underscore id and then we say update seems like there's some issue let's go to the mongodb documentation it says updating okay so we need to update one providing first the id and then the collection we can do that also okay let's try this one first and i say request dot body and we are going to update the first one which is this and something bad happening oh once again i forgot to have a sync here and reload yeah so we need to copy this one id and change let's say change the title okay so i will go here change it to patch request and i will provide it like slash id and i just say i title is updated title let's see what's going to happen we are not returning anything oh we are not returning and we need to say this is await and return response.json data this book is updated okay that's cool click on send and it says nothing is there some error is here it says find and update is not a function okay so maybe we need to just say update and can we do this update one yeah update one is there now what we have inside the update one first is the filter and second is the document to update so i think we need to find with the id and then request dot body is this going to work let's try send this is also not going to work update document required atomic operation so something is cool here so actually we need to say here something like this and then you can see we are here and says set dollar set and then provide the data so i say dollar set and provide request body let's one more try and yeah it says book is updated if book is really updated it should be updated here on our browser and yeah title is here updated cool and final thing final thing is delete and it should be exactly similar to all these things and now what i will do i will get it i will have it and then i say delete one and deleting with this id once it is deleted then i need to say book is deleted cool okay so this is done and here once again click on send it is not going to delete it some once again i always forgot this okay so final thought here it's updated why it's updated because it says updated because we are sending the patch request we need to send the get a delete request send and it says deleted that means if i go on the collection run it boom that's gone whoa we have done a crud operation and created a crud api with js one thing to notice here is that although we are deleting we are getting 200 when we try to update still we are getting 200 when we create let's say we are going to create one so second book and author is once again unknown send it still we are having some bad thing we need to say send you can see it should be 201 so how we can update the status for each and every request we are having so first whenever we get something yes we need 200 that's okay but when we create something we need the status to be 201 so can we do like status and like here but it's not given so actually first we need to say dot status and we say 201 which is created one and that's good so let's say third book and send it now this time it says 201 cool similar to that we need to do this and on the update we can have it but on the delete we should have a status of um it should be like 203 what what should be the 203 let's see no content so status code for no content uh 204 what about 203 status code of 203 uh-huh this one is bad okay so maybe we can say 204 and try to delete this one last one okay remove this third one i want to delete click send to 04 no content and the point is this no is really have no content so we can remove it okay so we have seen how we can do all the crud now what next you can see this is a route file this should not be responsible for doing all the database queries and doing all these things we need to work on the controllers now we need to work on the controllers so what is controller controller is just going to handle the request and do the stuff that is required this route file is not responsible for all these things it should be done in the controller so let's create a controllers controllers so controllers and here i will create the book controller so i say book controller dot js so what we have to do here we just need to export exports a function called index and this should be a a think function and we can also use an arrow function if we want but what this function is going to do this function is going to do whatever we have here so this part we cut and paste it here just like this that's it that's really the thing we need so here we need to first import const book controller is equal to require require go once up book controller and then we say hey book controller dot and we have the index cool that's it that's the only thing reload this and it's not working something is wrong here it says await on connect so it need the connect method so let's move this connect from here to here so it's using this connect and that's that's it i think reload and yep it's working okay so similar to this index we can do for every other one so this is the post one which is for create so we need to say exports dot create or maybe store actually and put this right here okay that's good so this time i say book controller dot store similar to this i need to show a book so now this time exports dot show is this one one more time this will be imported from mongodb otherwise it will complain about this and i say book controller dot show everything will be managed easily and this one is update so at last exports dot update is equal to this one do we have anything special no so that's okay this time book controller dot update and finally the delete or destroy exports dot let's say delete and this one oops is going to be like this everything is done finally book controller dot delete and you can see this looks so so easy now we don't need this connect we don't need this book id and just using the controller we have cleaned our routes file which is having all the information here but still having very less one two three four five six line of code only every logic is now moved to the book controller and book controller is having all the information about what's happening for every route and every function we have here so let's see yes it is working and let's get this one like here yeah this is also working and that means other will also going to work this is how we add a controller in our in our express or node.js application to reduce the work on our routes file let's take another step ahead and we can see everything we are doing every time we need to connect with the database every time we need to find which collection we need to work on and that's not a bad thing but we can improve over it for that to have the connection directly with the mongodb we are going to use another package called mongoose so if i go on this on the guide of database integration go to the mongodb you can see at last it say if you want the object model driven mongodb look at mongoose package so i will use the mongoose package here we are but it's good to get it from the npm mongoose here we are go on this and we have here so let's install this and see how this is going to work okay so first install this while this is installing let's see how we can use it first we need to install it which we have done then it says that you need to import it we will do that by using the require then we say that it says that you need to use the mongoose to connect with the database not the normal mongodb connection once that is done then you need to define some model now what is a model model actually a file or a class you can say which is directly connected to a single collection so if i create a blog post uh model that model will be responsible for the blog post collection or think about blog post table and we need to define each and every field on that why because what we are doing here is not a bad but we have some error suppose we are trying to store something with one more extra field so with this i say um key which is a random thing and it's not actually required in our application so how we can actually work over this if i try to create new book and send it it says still it is created with the key and if i try to see all the books this book has the key field which i don't want so that's why we need to have all these things and with that we have the validator on this mongoose mongoose provide various other things like middleware also and yeah we can work on it let's start with mongoose so now i will go directly on the main dot js file and here first we need to connect with the database and we have the db here but this is for the mongodb but we need for the our mongoose how we can do that we need this thing so like here and then we need to paste it and import the mongoose but since this is an await that means we need to create a normal function which should be like connect db and it's a sync function move this here and then the url is something like this and my database name is this one you can make it dynamic you can create the db name constant and do that but it's okay for me finally you just need to say module dot oops not model module dot exports is db connection and that's it this is the only thing we need to do and now we need to go to the main dot js and here we say const connect db is equal to require from like from database oops it's actually database slash db and then we say um a weight of connect db is this going to work let's see okay so it says await should not be used directly uh so we can just say db dot connect db and then we can start the server so what we can do here we can say connect db dot then and once this is connected then start the server if you don't want to do this function you can directly use you can directly use this mongoose connect exactly like here so like this and remove the connect and this will be good but i would like to move things which is responsible in its own place okay so this is done and you can see so now server should work reload it's not working it says db.collection is not there okay it's not working on our controller so to have all the books from our collection we need to create book model how we can create the model it says you need to use this like here the schema from mongoose scheme get the object id and finally we can create the new schema and at last we can export that yeah something like this okay so for that let's create another directory called models models and here we are creating book.js it's a book model first import the schema so schema will be like mongoose dot schema so maybe i can directly do that so what i have to do new schema okay so const book is schema is equal to schema and this is a new and here we can provide various things like title and author and anything else we want so first is title what is the type of this title it's going to be the string and then author is also going to be the string now finally we just need to say more module dot exports and exporting first await for mongoose dot and this should be like here what is that yeah mongoose dot model model and model name is book and the schema is book skimmer and we don't need this okay now we have the schema which is very nice and now we can use this schema on our controller on the controller go here we don't need the connection for the database we don't need to import any connect method and we don't need to do something like this so how do we do that we say books is equal to book model like here dot and you can see we have the find cool and finding is done so let's try this and reload and something bad happened it says where is that server reload okay something is not working oh i think i got it it should be await and it's giving me empty why this is happening because you know we are defining this model and every time you define a model mongoose will find the collection for books and what is the collection name in our case it's only book so how we can override it so we need to provide the third argument as the collection name which is book in our case reload and yes you can see it's working so i can totally remove these things and i totally remove this connect part and that's that's it let's just fetch a single one so instead of doing all these things i just need to say const book is equal to a weight of book model dot find and defined by id so how we can find it so let's do this and we need to do the find finding with the id i think yeah that's just the id let's try it with just the id not any other thing so maybe i can just provide the id and i can remove this like here and it should work so let's see reload and yes it's working this means it should also work for create and update how we can update it so first we need to get it so we can say update where is on the mongoose mongoose says update you can also find one find by id and update so model dot update should be that the thing so it should be like a weight of book dot update 1 and that's exactly going to be the same thing so let's cut that paste it here and not here here and this should be the thing okay let's try this on our insomnia let's go and update it updating with this this one and let's try another one which is the second one let's try with the second one zoom for you go with the patch and author is going to be the second second book updated click on send and it says book is updated reload and yeah second book updated this is very very nice and finally we need to say await book dot delete one and delete one with the underscore of id see how easy and how clean is this all the responsibility of selecting which collection we need to do is inside this model we are having the title here and we are only getting these fields which we have next we have more things in more things inside this mongoose and we can get that and now let's work on the validation because we can add anything in our database and we don't want to do that so what we need first we need to say await book dot store like this is this a store thing so or it's a create find create one not that yeah create a new blog post so it says new blog that's different thing save actually there is a save thing save no save is not there store is there anyways credential credential what we can say we can say create how do we have that on the previous thing insert the word insert i was missing so insert one maybe and then we can say request dot body but we need to actually do the validation so suppose i try to post without any author name so i say author name is not there and title is actually a number so how this is going to work click on send and it says unexpected token so something bad happened on our side so let's see so where is the issue seems like something is not good here anyways so we have the issue here okay so send it now server is crashed and this time it says is not a function so there is insert maybe insert should be there click on send it's not having insert also so maybe i can try this store that's big changes here click on store and store is not also not there what happening here uh do we have the create okay so create is there oh that's really bad okay so finally we can see title is there and title is we are sending the title as a number it received as a string and even though it has stored and also there is no author how we can restrict these things to be happening so first it says that go to books and here we define it as a string the type so we can also define type as string and we can say required is true how do i know go to the mongoose and go up check for validators in the validators you can see we can define like this type and required that's the only thing we need to do so we have the same for our author and that's it that's the only thing we need to do now what next if i try to create once again click on send it says something bad happened but this time it says hey there is a failed book validation and we can actually return these error to our user when we are trying to create so we need to use the try catch so try catch so on the try we try this if everything is fine return it otherwise we get the error we say response dot json for error okay let's once again try click on send and now we have a lot of things but on these we just need the error not other information okay so we can say errors error dot errors okay once again send and boom we have it it says author name validation error message but author is required so this is how we do the required validation now this is your challenge to check for the number validation why we are still getting this inside the database because we are defining that is whatever you are storing store it as a string but we don't want to even accept the number and try to convert it into the string okay so that's the thing we need and this is for the mongoose validation wow now is the time for the authentication now how do we do the authentication using this mongoose model and the jwt first let's create a route for sign up and for that we need to go into the into the routes directory and create auth.js and here we need to actually uh use this express and then we say const auth routes is equal to how do we do that on on the book i can check expert sort route yeah express press dot router and then we say auth routes dot on the route of slash auth then dot post for sign up when we do the sign up we need to do something and since we know the structure we will go with the auth controller directory dot sign up so let's go on the auth controller we need to create it so let's say auth controller dot js and here let's say exports dot sign up is going to be an async function a sync function which will do the sign up okay so everything is fine and for now let's return the json response dot json while it's doing this with me or jason and here is something something so request and response is here and i don't need any arrow for here oops i need arrow but i don't need the dot we need the comma is this working let's see we will go to the insomnia go to the slash auth slash sign up on the post request and click on send it says page not found boom because we need to register this route on our index so here once everything is done we can say slash of auth and then auth router like this which we can import from auth router import from auth and since we are defining auth here we can remove that from here or we can remove the auth directly here so let's have some different thing now this is registered let's once again try on insomnia it says could not find the server something bad happened every time i need to check auth controller oops i need to import the auth controller here so const auth controller is required from go one step up controller and auth controller is this okay let's send still we have one more error so let's see what's the new error it says route.post required a callback but got a object string so what happened here we are defining it like this is this the exact thing we are doing yeah we are doing right exports dot index and do the function so export dot sign up do the thing and dot sign up is the proper thing so slash sign up it should be working but it's not oh is it yeah it's also the post request auth controller what happened here the route dot post required a callback function but got an string object this is the exact way we are doing here oh we got the point yeah so what we have done here we need to actually remove this route and we just say sign up and then we need to get back to our index with the auth thing and yeah this is good now it will surely going to work click on send and this sure is not that sure okay router dot use required of middleware and got a function but we need to export it module module dot exports is equal to auth routes this time 100 sure it's still going to work okay yeah it's working what next we need to get the data from our request and then we store that on a user collection that means we need a model a user model so go to the models directory and copy paste for book call it user and we call this user schema and this will be user and since we are starting fresh we don't need to define the collection name it will use the users collection okay user will have name and then email and then password field which should be once again type of string and when we create it it's required true okay everything is done user model is done so let's go to the auth controller here i say await user dot create with request dot body and once it is done uh we need to return the user const user is equal to return the user like this okay so this is this is the way we can have it so let's try to create the user first we need the name so name will be sarthak why we are having this then email is going to be sarthak at bitfilms.com and finally the password should be password let's now see what's going to happen when we click on send it says server returned nothing no data and that's why it's giving error it says you are using await and user is not defined so user we need to import the user model so first we need to say const user is equal to require off go once up and use the user model okay that's it one more try click on send and yeah we can see we have the user detail but the point here is this user should not be there because this password is not encrypted we need the encrypted password in our database okay so we need to use a big crypt library from npm be crypt and go here so install this big crypt library once again it's so easy things because we know how do we decrypt the password we just need to import this bigrip library and then we can simply use some bicrypt.generatesalt to hash a password we can just say bigrip.hash salt around and the callback function if we need to have okay salt round is 10 so let's copy these two things go here and paste it bigcrypt is there now what's going to happen here we say const data is equal to which is like request dot body but we will spread it and then we say password pass word is going to be the password we will create password is equal to the crypt dot hashing the request dot body dot password and how it's going to do hash and then the salt around so do we really need the salt data salt around i don't know if we can go here it's not given that it is required or not anyways we can have the salt around so salt around is here then we can just say the body or data is this one create this user okay let's go and once again click on send and we have some error and i think this is because of await we have yes this should be await and click on send this time you can see we have the encrypted password so now we have the user we need to get the user on the login part let's do the login okay so next is the sign up so exports dot sign in or login maybe we can call it let's call it login then async request response of something something and we will create the user here or we will get the user here so let's go to the auth route here let's create another one which is for the post request of login and it will go to the login and for now to check i just say response.json and i say something something like this this time i will check for slash auth slash login and it should return me something something yeah asdf asdf this is working but now we need to fetch first user with the email okay so we can do that and we can say const user is equal to we have the user model then we say find one okay and it's going to only find one user with the email which we have from request dot body dot email okay so let's return the user if we get it okay so let's try to send the email which is there and no name we will send click on send it says nothing i think i again forgot to have the await click on send yes we have the user but you can see it's returning old user so i can just actually remove this user by going here so i say db dot users dot remove with the id of object id of this one and it's doing something i don't know what happened so once again click it is still there db.users.find all yeah we have it so what's happening here i want to remove this user so let's do that remove remove remove remove remove everything and this time i say dot users dot remove and this one and oh it's it has to be inside an object okay so it's now deleted close the terminal or maybe i can keep it running then once again if i try this time it's getting the correct user with the hashed password now since we have the user but what if we provide some different uh different different different email so first we need to check if there is no user then we can say response dot json and we can say error is user not found simple and if i change the user email it says user not found and it should not be 200 it should be 404 so status status is equal to 404 not found okay so change it yeah not found okay next we need to check for the password hashing if the password is really hashed or not so for that once again the the bikrit library will going to help bikrid dot crypt dot and uh compare or what is that compare yeah i think it's compare so let's go here on the big crypt documentation and it says that once you need to check to check for the password you can say compare the plain text and the hash and that's it so compare with the plain text is request dot body dot password and hashed one is user dot password because user is having user collection is having hashed password if this doesn't match then we say once again user not found so we have this and this time yes you can see we are having the password but we can change the password and then we try it is still returning that user so compare comparing should be false but it's not get false so let's try to send it oh it's again pending because it's an await thing a wait off this and send it and now it says once again user not found because the password is incorrect if i do the correct password it says could not connect to server something bad happen once again cannot set header after they are sent so these are the things which is creating the issue so we actually need to do something else so what we can do we can just return and kill the function if these things happening then we are good to go okay so we are providing good content everything is fine and we are getting the user back okay so we are successful on finding the user while doing the login but when we do the login we need the authentication auth token or access token maybe how do we do that let's do that that with the jwt you know i have this amazing video of jwt explained and this has got 221k views and it is going to explain you the jwt but i also want to explain you jwt right now so i will go to the jwt dot io website and here it's the jwt so jwt consists of three things one is the header another is the payload and finally the verify signature so if anything changes here this is not going to match or it will create invalid jwt you can see it's invalid and now it's verified valid so first one we have some data second one we have some data for our case like first one is having data for the jwt related like algorithm what is the type payload is the real data we have we can put the user information here and verify signature is obviously for the verifying of this dwt token but how do we use that in our node application so we need the jwt package so just the jwt let's search for gwt yeah exact match here we are so we are here and let's install the jwt on our application so it's installing how do we use it we need to go to some yeah here we are slight adaptation of jwt for nodejs is this the correct one i'm doing no this is not the correct one because we don't want jwt we need the json web token library which is very famous and yeah this one is the thing we need so here you can see it installation is failed i'm going to install this one the jwt json web token once it is done and let's see how we can use this one okay so first we need to require it and we can create the token by using the sign and we provide the information and then we provide the code hashing code okay so we can define some algorithm i think but that's not the thing we can define it synchronously or asynchronously it's up to us cool let's do that so once we are trying to log in the user we need to create the jwt so how we can create we need to use the jwt we need to import it and not like this we need to import like here so use this jwt here dot sign we need to sign the jwt and signing with all the information we want to add here so we need to add the user detail so we say user because we have the user okay we are sending all the user then we provide some secret so jwt secret we should move it on any env file but for now we call it fake jwt secret okay this is going to return me the token and it should be await thing once we have the token along with the user we can also return the access token okay and token is like this that's good now we have the token and then let's see how this is going to work click on send this time we have a lot of other things also so yes we have the token so you can see we have this token access token but we have some other information which we don't want so what if i just return the user and then we need the access token so send it ha this is good so user information is this an access token is this okay so we get the access token it's using the using this login system and we can use this access token to access some protected routes this means we need the middleware in express.js how do we do that to understand the middleware in express.js we can go to this guide and writing the middleware it has given very nice information here so it says that what we are having here first you can see this get is actually the http method this is actually the path or the route then we can define a middleware middleware function and that should be the thing so middleware function which we have the request response and the next thing now what is the middleware middleware is like a guard which will protect the code to execute on the further or not so it will say that okay something is good go again but if something is bad stop here right so how do we write our middleware so to create a middleware like middleware like logger you can see we need this function which will do something and finally we say next go to the next request and when we have this middleware we can just say use this middleware okay so we have it now let's create a directory called middleware [Music] inside this i will create test.js or test middleware this is just going to say export dot exports dot test is equal to it's going to have a function an arrow function it could be this will need request response and next part and let's lock this and say i am test middleware and it's very important to go with the next otherwise express js will not move further how do we use this middleware go to the main function or main.js first import this const const test is equal to require the middleware so go to the slash middleware why it's not doing that yeah middleware test and then finally we can say that app.use test which is the test middleware now this is going to apply for full application but let's see it says something bad happened app.use requires a middleware function we are giving it okay so maybe what we can do we can say const test and then module dot exports is equal to test now this is giving the actual exact one now if i reload this yeah you can see everything is fine but every time we do anything here on our application this is going to be logged if we try to fetch a user you can see we are getting it and once again it is locked so every time and for every request this one is going to work this middleware is going to work but what if i just comment this next see this is going to be fun it's keep on loading because it don't know what we have to do after this log so after this log it is stopped so that's why we need the next one so reload yep logged and next is there cool that's how we create the middleware in express.js which is absolutely fine but middleware are this one this middleware which we have created is added to all of the routes in our application but we want that to be on a specific route our auth route should be on our auth middleware should be only on some of the routes so suppose we want to add this test route not here on every application but on very specific route so suppose we have this routes directory we have this books book route and now i only want to add it let's let's first try with this one so i only want on the home page which is this one so let's see on the second parameter we can say first import this test middleware and say test and then third parameter will be like the callback okay see this we have some issue it says can't find okay so we need to do something like go on the middleware and then on the test is it fine yeah now if i reload on a single book route you can see there is no log but if i go on base url then you can see we have the route and this is the thing we really need we want to add some route on a specific we want to add this middleware on specific routes only let's get back and we don't want any update here we want to add the middleware on these routes only so how do we add here for this since this is actually a router so we can say book router dot use and using our test middleware so we can say this is the test middleware and importing easily like this and now whenever we go on home page like this you can see there is no log but if i go on any related to book route we have the log now that's the simple thing this is the only concept you need to learn about the middleware let's change the name from auth test to auth so this will become auth and now here we are using this auth middleware so change the name once again to auth okay so now this is this means that these routes are only be accessible if this middleware will allow okay this is good but how do we check for the user this is real issue so see can we just return any error from here so we have the response and we can say response dot json and we can simply say error and um un authorized like this and status we can also define dot status is equal to 404 222 i think no it is unaccessible entity what is unauthorized unauthorized code which is 401 okay so 401 and that should be the thing so what if i try to get a user uh get a book all the book let's see it says unauthorized that's okay that's really fine so we just need to check for the user and how do we actually get the user and we can verify we need to verify through the header through the token user is going to send so let's do that validation or authorization now the normal flow for any authorization is like first we call the user we get the user token like this we copy that token like here and then after this we can go to any protected route if we send the query right like this it says unauthorized 401 but we need to send the authentication token or authorization token as like bearer and whatever the token is now if i send it it should give us the real content because now we have the valid token but how do we check for the token first let's see if i say request dot headers because we are sending this on the headers if i go and check for this now i need to send it you can see i have this authorization token so i can say dot authorization which is having all this br token okay so send it yep we have the bearer token now first we need to check if there is request dot header so suppose we don't have any headers also we need to check for if there is a header then we need to check for any authorization token so so after this and end request dot headers dot authorization if there is authorization we need to check for third thing request dot headers dot authorization dot is split because remember we are getting bearer we don't want beta we just need after this space so split with the space and get the first one if all these things are good then console log me the token and i say let token is equal to this it's not doing like here maybe we can maybe we can just get this like here so give me that like here okay so it should give me just the token only nothing else send it yeah we are just getting the token and nothing else okay so we have the token so i say const token is equal to this one now if we don't have any of these things then we say it is unauthorized okay or maybe we will do that later but first we are here now what we have to do here now we just need to say jwt which we have on our auth controller so copy that and i want to use the const jwt dot verify verifying this token so token is there but with the secret remember we have the secret here on auth controller which is this one fake jwt secret so i put it this and third is the callback what's going to happen so first we are getting error and then we get the response i think or maybe we can call decode okay now if there is an error then i just return it okay otherwise we can check for the decode so it should be decode not like this decode so how do we decode let's go to the jwt documentation and it says signing is done we need the verification okay so it says token secret verification and we get the foo or whatever the decoded part remember the jwt here this is the payload so on the decoded part we get the payload i think and if i am thinking right then we should get everything right okay let's get back to our code what we are sending on the decodes let's just log and see what we have on the decode part although we are sending unauthorized so it should be unauthorized but we have user and we have the user id we can verify these things like we can say dot user dot underscore id okay so we are done with this and now we can say user model we can use the user model like here dot find one so finding one with our underscore id as object id of mongodb and using this id now we need to say await and remember if we are using a weight it should be a sink here so now user is there if user is not there then also i'm going to return that means i'm not doing anything it will go outside it and finally it will return 401 but if there is any user then we need to run as the next that means the token is valid okay lot of things but a weight is only valid oops it should be a sync here first not here that's good yep and finally if i try to send it oh again it's returning that so cannot set a header okay now remember we have also one more thing which is the async await way of it verifying so i say like const const verified is equal to await a weight of jwt all these things and or maybe just let's do that const verified is equal to this and let's just comment this and try to log verified what we are getting on the verified so everything is good click on send and it's spending it's pending that means we can use a weight here and then a sync here and in that case we don't want to do all these callback thing so let's try to check what we are getting now send it we get error or we get the response so first we need to say if try a catch if this is good then we do something if there is some error we do something else so if this is nice then we should return next but we need to verify the user also so remember we have these things so like this if there is any error then we need to return this thing on the catch part okay and if some if user is not there then also we need to return this like here okay and if user is there then we just need to say next and we end this function right here so that it will not go on the next part so instead of this i can do something like this okay so first we are doing await then we check for the user if there is any user if user is not there then unauthorize and return that means close this function otherwise if user is there go to the next part cool so let's try this sent and still we are getting 404 401 why 401 so let's try to log error let's see what's going to happen click on send and the code is not defined ah the code is not defined so we need to say the code the code will go here now send and boom we can see we have author we have title and it says all these fields required because i'm doing something bad it's it should be something what we are doing oh we are trying to create the book and that's how it's working you can see it is working now if i change anything in our token let's say i remove that e then send it says unauthorized because now token is incorrect so this is how we actually check for validation and check for all other things which we require anyways this is all about the express.js node.js validation connection to the database i think you got the point how you can master this node.js and understand each and every concept if you like this episode please give it a thumbs up which is very important and subscribe to bitfume's youtube channel you will meet in some other videos till then good bye
Info
Channel: Bitfumes
Views: 27,003
Rating: undefined out of 5
Keywords: nodejs course, nodejs full course, nodejs 2022 course, node tutorial, nodejs best course, node js best course, nodejs event loop explained, nodejs mongodb, nodejs full course 2022, nodejs bitfumes, nodejs beginner, node js full tutorial, node mongoose, node js projects, express tutorial, nodejs crash course, node js explained, bitfumes nodejs, node js complete tutorial, nodejs expressjs, node js 2022
Id: hKyudh3rC_A
Channel Id: undefined
Length: 214min 15sec (12855 seconds)
Published: Tue Aug 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.