Getting Data from the Backend (Node.js/Express) to the Frontend (JavaScript)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so the next thing that we're going to take a look at here is how to run JavaScript on the back end right now I'm doing this because I realize that for many of you your main motivation for learning JavaScript May well be to use it on the back end so I'm going to be showing you right now two different ways of running JavaScript code using node.js now the first thing you're going to want to do is actually download and install node.js on your computer and what you're going to want to do first of all is find out whether you already have those things installed right you may well already have them installed and in that case you may not need to download and install it as I'm going to show you so the way that you're going to find out whether you have node installed is by typing node-v in your terminal and if you have node installed what it will do is show you the current version of node that you have installed now the version that I have here is almost up to date the current version is actually 16.14 at the time of recording at the time you're watching this it's probably something higher um but you're just going to want to make sure that you have a fairly up-to-date version preferably V16 or higher as the first number and the other thing you're going to want to check as well is the version of npm now we haven't actually talked about what npm is basically npm is a tool that you can use in conjunction with node to install other people's code into your projects we'll talk about this in much more detail later on but for now you're just going to want to run npm-v and if you have node and npm installed you should see a version for that as well if you just see something like command not found then that means you don't have it installed and you'll need to do the instructions I'm about to show you so assuming that you don't have node and npm installed what you're going to want to do is go to nodejs.org and you're going to want to download it now on this page there are two main options that you have for downloading node.js one is the long-term support version and the other is What's called the current version now for most people right as node.js's website itself says the long-term support version is going to be what's recommended right it says recommended for most users so what I'm going to recommend you do is click on this button which will download the package for installing node.js and once that's completed you're going to want to click on that and it will walk you through the installer wizard now if you are feeling more adventurous I wouldn't recommend this right now but if you ever want to work with the latest features of node.js all you would need to do is just come in here and select the current version instead and again you're probably going to be seeing different versions of this than I am right now because chances are versions will have advanced quite a bit since I recorded this but everything that I'm about to show you will still work exactly the same way alright so let's click on the installer that we just downloaded and what that's going to do is open up the installer wizard we're just going to click on continue agree and install and what that will do is it'll probably ask you for your password so I'm going to enter mine there and then what we're going to see is it'll just install everything for us it usually takes you know a few seconds Max and then of course uh depending on your operating system you're going to want to follow the directions that it displays here I've already done that myself so I'm not going to do that again and we're just going to click on close all right so now that we've installed node.js we should be able to go back to our terminal here and we may want to close it and reopen it just just to restart the terminal oops it looks like we need to click on the trash can button instead and then we'll open up a new one here and now what should happen is if we run node-v we should see that we have the latest version that we saw inside here right the long term support version that is displayed there and if you run npm-v you may see a different version there as well now npm is actually bundled with node so by installing node as we just did you're going to have access to npm as well right you don't need to install that as a separate thing okay so now that we've installed called node.js and npm locally I'm going to show you how to run backend JavaScript code using node what we're going to do here is we're going to start off by just creating a new express application it's going to be a very simple project so actually I'm just inside this folder called Express course and inside here I'm going to create a new folder which I'll open up in my IDE and we'll just call this new folder something like front end Basics and I'm just going to open this up in my terminal by saying code and then front and Basics and that'll open that up in another IDE window cool so first things first let's just initialize this as a new npm package by saying npm init Dash y that'll create the package.json file for us and then we're going to go and install Express by saying npm install Express and once we've done that we can create our new server by just creating a new file and actually I'll create a new folder called source and inside here I'll create a new file called server.js and then we're just going to set up a very simple Express server by saying import Express from Express and then we'll say const app equals Express there we go and then we'll tell our app to start listening by saying app Dot listen and we're going to have it listen on port 8080 and then inside this callback here just like we've done uh previously we'll say console.log server is listening on Port 8080. so none of that should be new to you I'm sure you could do that probably with your eyes closed at this point but nevertheless we now have a handy Express server that we can use for demonstration purposes alright so the next thing that we're going to do here is create a file that we're going to send back to the front end when the front end sends a request to our server and this is the first step really in starting to execute some of our code on the front end is we're going to need to send the front end a file containing some sort of code that we want it to execute so what this is going to look like in our first example here is when our server receives a request from the client the server is going to send back a file and this is going to be an HTML file by the way containing some scripts inside of it we'll talk a little bit more about how that works in a minute and when the client receives this file what it's going to do is it's going to render all of the HTML right and by the way we're going to be sending this request using a browser on the client side instead of something like Postman although it's perfectly possible to use Postman for this testing as well but so when the browser receives this file from our server what it's going to do is I said is go through and render the HTML and somewhere in that HTML we're going to add a script tag with some JavaScript code inside of it right so we'll be able to execute front-end JavaScript code and what the browser is going to do when it reaches that script tag is it's going to automatically execute the code that that script contains so this is how we are really able to start defining what we want the browser to execute from on the back end is we can just choose what sort of JavaScript code we want to put in this file we're sending back okay so in order to do this what we're going to do is just create a simple HTML file and you can create that just inside this Source directory as well so we'll say new file and then we'll say we'll just call it index.html I suppose and let's just set up a very simple HTML file here we're going to have the doctype HTML then inside the HTML tags we'll have the head and let's just add a title to this page we'll say something like front-end execution test and then for the body we're just going to have a simple H1 heading that says something like this is a test right that's not really necessary but it just gives us something to display in the browser so that we can see we've actually received the file and underneath this and really this could be anywhere in the HTML document we'll discuss that in a little bit more detail later on underneath this we're going to put a script and in between those script tags as I said we can start writing JavaScript code so the simplest piece of code that's really only available in front end JavaScript for the most part is going to be a function called alert which will just display a little pop-up window in the browser you'll see what that looks like in a minute but what we're going to do is have that alert say something like hello from the front end okay so that's our simple index.html file so now what we're going to need to do is have our server send that file back to the front end as a response when it receives a request so what we're going to do is just Define a simple get endpoint that will listen on the Home Route and then inside the Callback here we're going to have the request and responsive course and in order to send back a response with that HTML file in it what we're going to do is say response dot send file so this is the function that we're going to use to send back files specifically to the front end right instead of doing something like response.json when we wanted to send back Json data so response.send file and then we just need to provide the path to the file we want to send back which is of course going to be actually we'll import the path Library here so we'll say import path from path and then down here we're going to say path dot join and inside here we'll say underscore underscore directory name and this is just going to be index.html okay so now that we've done that we should be able to load this index.html file by sending a request to our server from our browser so what we're going to do is start up our server by just saying node server.js and oops that should actually be Source server.js there we go and oops it looks like we got another error because of the import statements and actually in order to avoid having to do all the funny stuff with this directory name thing here when we convert our project to module I'm just going to switch these things up here to require statements so we'll say const Express equals require Express and same thing with path we'll just say const path equals require path okay so let's try this again we're just going to run our code one more time and sure enough we see Server is listening on port 8080 and if we go over to our browser now and go to localhost 8080. sure enough we'll see that our code is executed and we get this little pop-up window which is an alert that says hello from the front end okay and if we click OK we'll see that everything else will be rendered in the browser so again what's happened here is our browser I'm just going to draw this out one last time here to make sure we have the visuals to go along with it what's happening is we have our server running over here and our browser over here sends a request to the server the server sends back that index.html file to the browser and then our browser basically goes through that file uh you know parses all of the HTML and when it reaches that script it executes the script and that's where we see the little alert displayed okay so we were successfully able to run a little bit of JavaScript code in the browser now which is our first piece of front-end executions alright so if you want to play around with this a little bit what you can do is just change some of the code that's in this alert if you want to right you can write the same kind of JavaScript for the most part that you can write on the back end there are obviously some things you can't do like you can't access the file system like you can on the back end because well obviously the browser isn't going to let you access your users file systems on the computer they're visiting your site on you know but if you wanted to do something for example like log something out to the console right console.log works on the front end just like on the back end but what it's actually going to do is print that out to a slightly different place so just to show you what this looks like we're going to say console.log and again we'll say hello from the front end and if we head back to our browser now and hit refresh what this is going to do is send another request to the server and load that updated index.html file with the changes we just created and actually as a matter of fact we need to restart our server so what we're going to do actually in order to avoid having to restart our server every time we make a change we're just going to say npm install save Dev node demon okay so we're installing the node demon package and we're going to use that to run our server continuously so once that installs here just give that a moment and then we can run our application by saying no demon and source server.js oops and that should be npx no demon Source server.js okay so now that we have our server running we should be able to go back to our browser and hit refresh and what we see here now is the new index.html file that we received that's not really obvious because there was no change here but uh we know that because the alert wasn't displayed again so if you want to see what we logged out to the console on the front end what you can do is right click and then click on inspect and if you go to the console sure enough you'll see the message there that says hello from the front end so this is the front end console right this is where things will be logged out when you say console.log on the front end and on the back end obviously if you log something out you're going to see that in the terminal all right so anyway what we've seen here is the basics of executing code on the front end when we wrote the code as part of an express application so far it might not be apparent to you what sorts of things we might actually want to do on the front end right in other words what are some things that we could do on the front end that would actually be helpful to our app as a whole instead of just doing things like displaying an alert or logging to the console well that's what we're going to take a look at here and one of the first things we're going to take a look at is in my opinion one of the most effective things that front-end code can do what we're going to take a look at is how to have our front end code load data from our backend code so in other words the logic that we put inside these script tags here many times is going to want to have access to some sort of application data right if we were creating some sort of e-commerce site that displayed all of the products all of their prices Etc right I'm just going to draw those like this then obviously we're going to want our front end to be able to load all of that product data so that it can display it in the interface here right and we're also going to want the front end to be able to do things like add items to cart when the user clicks the button for an item and uh you know other things like that so in other words there are lots of situations where the front end is going to need access to the same sort of data that the back end usually gets to work with and in order to do this we're going to have to actually write some code inside our front end scripts that will itself make a request to the backend so this might sound a little bit confusing let me just draw this out again I'm going to be drawing the same server and computer probably about a hundred times during this course all right but just to try and make things extra clear for you when the client first requests the file from the back end right the back end is going to send back that index.html file and the browser is going to render that file inside itself so that we can see things like the interface and it's also going to run any scripts that it finds in the HTML all right now what we're going to do here is actually have the script itself which is uh hopefully you can see it represented by this inner box here we're going to have the script itself make a request to the server and the server is going to send back some sort of Json data that our front end will then be able to use all right so in other words there's two things going on here the first thing is the browser loading the initial file from our server right when we type localhost 8080 into our browser and hit enter all right and then the second thing is when our browser actually runs the front-end code that we wrote inside this script tag and that code makes a specific request to the server and gets a response back so hopefully that's making sense so far in order to make this work what we're going to do is open up our server.js file and we're going to create a separate endpoint that our front end code will be able to load data from so this endpoint up here was meant to allow the front end to load a file the one down here is going to send back some data so what we're going to do is we're going to say app.get and for the path here we're actually going to say slash API slash and then depending on what type of data we want to send back let's say that we want to do let's say that we just want to send back some simple user data okay we're going to say get slash API slash users and what this is going to do is it's simply going to return an array of JavaScript objects Each of which represents some sort of user data so what that's going to look like is we're going to say const users equals and then our first user will just have an ID of one two three and the name we'll do Sean and then the next user will say ID 234 name we'll do Bob and then ID 345 name Sue okay so this is obviously very simplified user data but the same process would apply regardless of how complex our data is so now that we have those users we're just going to send them back to the client Side by saying response.json users okay so now that we have these two endpoints what we're going to do is head over to the front end and instead of just logging something out to the console directly we're going to have our front-end code make a request to the back end now you might wonder how this is done programmatically right we were able to make a manual request just by entering in a URL to the browser and hitting enter but when we want our code to do it there's a specific function that we're going to use most of the time on the front end and that function is called Fetch right and in fact if you want to learn more about this just look up the fetch API this is a default API that we can use in front-end code that we can use to do things like send Network requests okay so using the fetch API is a pretty straightforward process really all that we have to do in most cases is say fetch right and this is automatically included right it's automatically available in our JavaScript code here we don't need to import it or anything and the fetch function can take a number of arguments but the simplest way to do it is just to pass the URL that we want to send this request to as the first argument so what this is going to look like is we're going to say slash API slash users okay and notice that we didn't need to include the full localhost 8080 thing because this index.html file is coming from localhost 8080 so that's just where the browser is automatically going to send these requests that we make with no domain name okay so saying fetch slash API slash users is going to send a request to the back end and the default request type of course is a get request so if we just want to send a get request to do something like load data which is the case here all we need to do is say fetch with the URL we don't need to specify any kind of options or pass any other arguments we'll see how to do that later on so the next thing that we're going to need to do is deal with the results of this fetch call now obviously Network requests such as this one are asynchronous right they take a long time so in order to avoid blocking the main thread the fetch API is going to use promises now what this means is we can get the result of calling fetch by just adding dot then onto the end of it and we can pass a callback function to this that is going to take the response as an argument and inside this callback function now we can do whatever we want with that response all right now one thing to know about this response that we get back from the fetch API is that in order to get the data it contains we actually need to call another function and return that from this dot then callback right so we're going to say response dot Json and this will give us a JavaScript object or array whatever the server sent back to us that we can work with so all that we need to do now is add another dot then onto the end of this and that will be the actual data right that's going to be our users that the server sent back so now what we can do is just say console.log and we're going to print those users out to the console here you could also display them in an alert if you wanted to but using console.log is usually the way that's recommended to you know debug and take a look at the results of JavaScript code so that's really all that we need to do again what this is going to do is when the browser runs this it's going to send a request to the endpoint that we defined on our server and this is going to send back the array of user data which will then be passed to this callback function we're going to convert that into an actual JavaScript object and we can use that final result inside this callback here for now all we're doing is logging that out so let's run this thing and see if it works what we're going to do is first of all you'll want to make sure that your server has restarted successfully it looks like mine has and now if we go back to the browser and hit refresh sure enough what we'll see is that inside the console here after our code is completed it's logged out the user data to the console and we see that we have all of our user data right here so in other words our front end now has access to all of this data that the back end sent over to it so if we wanted to do some sort of processing with these users right if we wanted to filter the users if we wanted to display them in the user interface somehow we could do that now that we have access to that data so anyway that's how to load data from the back end in front-end JavaScript code I hope this has been informative for you and I'd like to thank you for viewing
Info
Channel: CBT Nuggets
Views: 39,715
Rating: undefined out of 5
Keywords: cbt nuggets, it training, it jobs, it certification, it learning, it training program, tech learning, tech training, certification training, training courses, it career, career progression, it tutorial, e-learning
Id: C_vv1D5oDZ0
Channel Id: undefined
Length: 23min 59sec (1439 seconds)
Published: Thu Jun 29 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.