How To Connect React To A Backend (Express.js) - React for beginners #7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey Forge members and welcome to the seventh tutorial in this react series so in this tutorial I'm gonna show you how to connect react to a back-end this is something that I had a ton of trouble doing I found like maybe ten different medium articles online ten different tutorials online that I was trying to follow in order to do this and I found out it's actually really simple if you know the step so in this area I'm just gonna try and show you the simplest way to do it and to do it we are gonna be using a back-end frame we're in a back-end framework known as Express if you haven't used Express before don't worry it's very easy to use it's essentially just a back-end framework and what that means is you can make HTTP requests to it from your front-end and that will allow you to do things like if you want to connect to a database you can send an HTTP request from your front-end to your back-end which then queries it to your database and you're probably wondering well why do we need the data or why do we need the back in there why can't we just send it from the front-end and the reason is because your front-end renders on client side and what that means is everything that your front-end is doing will be accessible to your user and if you're querying a database you're probably going to be using things like credentials and you don't want your users to be able to see the credentials that you're using or anything else in that sort of sort so I'm gonna show you how to do it and the first thing we're gonna do is you can see here I'm gonna quickly remove I've created a folder and I've called it video 7 so here we can see like are all the other react applications we have made and I created a folder called video 7 and when you're making a project that has a back-end in the front end they're both separate projects there's separate node projects therefore you want to keep them in set separate you want to keep them in separate folders so I'm gonna go ahead and make a directory called my back-end and this will be where my back-end code is and when we're ready to make the react front-end I'm gonna make a specific directory for that so let's go ahead into my back-end and we're simply gonna follow the Express documentation on how to make a very simple Express project so first we're gonna think we're gonna do is we're gonna create an NPM project by doing NPM in it we're gonna keep all of this stuff to default for entry point you can keep everything as it is just click enter over and over again and you can see all that it'll generate is a package.json now the next thing we're gonna want to do is install and save Express so we can do NPM I express desta safe and this might take a little while it's pretty fast and what will happen when you do it is if you'll see that we have now a node modules a package left out JSON as well as our package out JSON and if we were to quickly look into a package JSON we'll see here that under dependencies Express is one of them so that's how you know that it is installed correctly so the next thing we're gonna want to do is set up a very very very simple back-end server so let's open up vs code and look at it through there so you can see here I'm gonna simply open up that same videos a folder that I had before and you're gonna see here it is so we have our package we have our package out JSON so we're now what we're gonna do is we're gonna create a I'll just move this over to the side we're gonna create a new JavaScript file and we can call it something like app KS now we can go ahead and copy all of this stuff on here so if we look over here we're gonna see pretty much all we're doing is we're getting a in JavaScript if you're not familiar all we're doing here is we're simply importing Express we're specifying a port now you should note that Express actually runs on the same default port as react which is 3000 so we can go ahead and change this to 5000 so it doesn't conflict with react when we get to it so now what it does is if you're not familiar with HTTP requests all that's gonna happen is if I were to send an HTTP request to localhost port 5000 slash it will send this string back hello world so what I'm gonna do is I'm going to type so all you have to do to run this is type node fjs oh don't forget to CD into the my backhand folder so now that I'm in this folder I could type node fjs and you'll see here it says example app listening on port 5000 so if I were to go to my web browser and I were to type in localhost 5000 you would see here it just returns a hello world on the page and this is actually easier way to Texas there is a tool that a lot of developers use and it's called postman and postman is used for testing your HTA your a HTTP request to a local back-end so our back-end is currently running locally on port 5000 so if I wanted to test the response all I would have to type in here is local host 5000 and then the endpoint that we have here which is know which is the slash and I click send and you'll see here that I get hello world back now if I were to create another one I can create another endpoint and I can make it called a slash new endpoint and then instead of sending hello world I can just send something like this is my new endpoint and you can see here that if I send it to hello world if I send it to slash it'll be the thing but if I have a new endpoint we can see here that I get oh did I spell everything properly oh you have to rerun it right so let me rerun it and now if I send the same request you'll see here it says this is my new employee and there's a way to get around our having to rerun it every time it's through this node this NPM dependency called node Mon which I will show you in another video but now that I have a very simple back and running let's um let's do something simple like return of the weather so I'm gonna make a API for my react app let's say I want to have a react app and on them in the middle of my react app I want to have a button and when I click that button it will query my back-end which will then get the current weather statistics for Toronto so I have gone ahead and signed up on the website called a pic zoo which gives you an API key a free API access to their weather API I used to use a weather open weather map I think is the name of the website for my weather API however it looks like they're dealing with some technical issues as their API Keys even with a verify account don't seem to work so I would go ahead and make a website on this website and you'll see here we can't actually test out this API on postmen before we actually move before we actually move over to Express so we'll see here we're making a get request arc our API key is here and then the city that we want to get the weather of is here we can go ahead and change that to Toronto and you'll see here it returns us this giant JSON with the actual weather and we can see the temperature in Celsius is currently 10 degrees Celsius in Toronto awesome so now what we want to do is we want to make it so that whenever we have an endpoint and whenever we hit that endpoint in our express it will simply return the weather in Toronto so we can go ahead and say make a new endpoint and call it something like I get Toronto or get weather Toronto and what we can do is just follow the same syntax and then here is where we can decide what we want to send so what we would do here is we would actually use a package to make an API request so in order to do this quickly we're just gonna use the request library in JavaScript we're simply gonna import it by making it a variable and then we're gonna take some basic request code so this guy right here all this is gonna do is it's gonna make an HTTP request to whatever URL you put here and then at the very end it's going to if there wasn't an error and the status code is 200 which means it is successful it's just gonna console.log what we have so we can go ahead and replace the Google with the weather API URL with your key and everything in there remember we're not trying to make an actual back-end we're just trying to get a proof of concept up and running so we can connect it to react and what we're gonna do is we're just gonna have res dot send and then the body which is our response so now if we come into here if we come back to here and we test our endpoint oh we have to restart it so let's quickly let's quickly cancel this and it seems like we have a syntax error so um oh that's weird it cannot OH so we have 2 n pm in npm install' request and what is once that is done we can go ahead and run our app and you'll see here if I now make a request to our endpoint we pretty much get the exact same thing as we got from our API it just looks a bit less nice if we format in JSON we can see here that it's pretty much the same data now let's filter this out so it's a bit nicer so all we actually see here is the temperature in Celsius so let's just simply add a line here to parse the body in JSON so that we can use it and let's create a variable for the temperature see if we remember I believe that it was under the current weather and then the temp underscore see so far temp C is equal to that and then when we send it we want to send it as a map like this so let's go ahead and type nodejs let's run our app again if we go to postman and we send it we can see that what we were getting back whenever we clear our endpoint is this map with one index which is a or one key which is temperature in Celsius is equal to 10 so we are pretty much done on the we are pretty much done on the back inside so let's open up a new terminal and let's create a reactive so create - react app and let's call it my front end and this will be in the same folder as video 7 but it's not in the same folder as the backend one so you can see here within video 7 we have my back end and my front end and they're two different folders and two different node projects which means the actual node dependencies are not shared between them as well so my front-end will not actually have you know the no dependencies like Express and requests that we installed on it within its package dot JSON which we'll see in just a second so now that is this is done installing we can go ahead and CD into the front end and we can type NPM start as we usually do and we'll see that it'll just start our default of our default react project so we'll see here and also if we take a look and go into the file structure we can see that everything is as it usually is so we'll come back here this is still loading we can go ahead and delete this test and for now let's keep most of let's keep most of this stuff in here I'm just gonna show you basically right okay so we can see that's working let's create a new component and we'll call this like I don't know whether Jas and in our weather yes we're just gonna create a standard react component and we'll say here the weather in Toronto is and we won't actually fill it out just quite yet so what we can also do is have button and we'll know that we'll have the button say get weather in Toronto Toronto and then we can go ahead and create a state so let's create a constructor and then call super and then let's just say this dot state is equal to and then in our state will set a weather variable and we'll have the weather set to zero by default or let yeah we'll have it set to or let's have it set to not yet gotten so then over here we can just have this call this that's date weather now let's go ahead and use our import our weather and let's let's delete all this stuff and just pop it in here so we can see here we're gonna come back and we'll say we'll feed the weather in Toronto is and then it's like not yet cotton and this button doesn't really do anything so now here is where the magic actually happens we're gonna now go ahead and link our react front-end with our express back in and this is how you do it we are gonna go into the package.json in our front-end and under private we're gonna add a new variable called proxy and what we're gonna do is we're gonna set that proxy to localhost of whatever our front end or whatever our back ends port was running on so in our case it was five thousand now what that does is if we ever make a request to an endpoint and it can't find it on the front end it will automatically try to get it on this port and I'll show you why that's useful let's go ahead and here and created a component didn't mount function come ponens and mount and when the component so in this component did malfunction what we're gonna want to do is let's say we want to just haven't make a very simple HTTP request to our back-end now what we're gonna do is we're gonna use another dependency another library called Axios which is a really a really good framework for making API requests within react so let's go ahead and come in here and we'll make another terminal and we're already in the front end so we'll do NPM I Axios and save it so while this is installing essentially what access is gonna do is we're gonna make an HTTP request to slash our endpoint and our endpoint was get weather in Toronto and when it sees that we're not able to find it on a react support which is three thousand it will check to see if the endpoint exists on our proxy which is which is the 5000 port and that's where it'll find our back end it'll query it and it will return the result in Axios now what we can do is we can go ahead and import Axios and now this is what the syntax will look like when we want to make the request so it's simply just calling the get method of Axios which denotes we want to make a get request and then the URL that we want to make the request to so in this case it is slash get weather toronto and then we have a function here that will tell us what to do now it's worth noting that if we want to be able to set the state and use the this keyword in here we we should switch it to the arrow functionality so this actually gets passed in now let's go ahead and see what happens so let's comment this out for now if we go ahead and console dot log just the response let's see what it looks like so this will run on component didn't melt which means it's already run and we look at our console and we can see here that it passes us this huge object that we're getting from our back-end it includes the headers the request object and the data that is actually being passed through so this is what we're interested in so if we type data we can come back and see that the data is the same temperature map that we were getting in postman so in this case all we really care about is the temperature so we would do response data dot empty now instead of console dot logging it let's set the state to it so we can say this dot set state and we're gonna make it so that weather is going to be equal to response data temp C oh and don't forget our curly braces here cool so now you'll see here as soon as we come on to the web page it'll show exactly what the weather in Toronto is and you'll notice from the beginning of a bit of video to here it decreased one temperature it's getting later here but let's just make this consistent and let's make it so that it only gets on when we click the button so we can change this Metheny to something like hand little button click and then add an onclick handler for this button okay so now if we come back when we first come here the weather will not be gone but as soon as we click get weather in Toronto BAM it updates to whatever the current weather in Toronto is so there you have it that is how you hook up an express back end to a react front end now it's worth noting when you're making API requests in a within react you actually don't want to have it in these type of places because sometimes those requests might take a while and it could cause your entire component to sort of hang and timeout if the request doesn't go through and the proper way to do that is by using another library known as a redux Agha or thunk either one of the two and in the next videos I'm gonna introduce you to what redux is because we're at that stage and then after that I'm gonna show you how to use redux saga and that will be where you'll see where to put your API requests for your back-end and the proper way to do it for development projects and production projects so thanks for watching and I'll see you guys in the next video
Info
Channel: Anthony Sistilli
Views: 127,946
Rating: undefined out of 5
Keywords: programming, React, React for beginners, React tutorial, React crash course, React lifecycle, Anthony sistilli, Beginners React, Componentdidupdate, ComponentdidMount, componentWillUnmount, React components, Lifecycle methods, Javascript React, ReactJS, React Browser Router, BrowserRouter, React Browserrouter, React routing, Routing, Frontend development
Id: kJA9rDX7azM
Channel Id: undefined
Length: 19min 44sec (1184 seconds)
Published: Sun May 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.