Introduction: Connecting React with Node.js
Welcome to this session on how to connect react.js with node.js. In this session, we are actually going to look at how do we connect react.js with node.js. So a very warm welcome to this session on react.js connectivity with node.js and in this session we are going to focus on how do we connect our react.js application with the node.js platform.
So we are going to dive into creating a hands-on demo which will have two parts to it. We would have the client application that we will first create as a react application. We will then create an express.js application with node.js and we will then try to connect both of those applications together.
So express.js is a rapid application development framework that allows us to create a web application very quickly on the node.js platform and we'll use it to create a custom API and then connect that endpoint to the react.js client application. So let's dive into our demo.
Environment Setup & Creating the React Client
Let's start with creating our client and node express applications and see how to set them up and then get them connected to each other. Let's start with our hands-on demo and we will first go to the node.js website nodejs.org. We can download the lts version which is a stable version of node.js. Moment I click on this it will prompt me for a download. It will download the msi file and then all I need to do is double click on it, keep clicking on the next button and install. That would install node.js for us.
Scaffolding and Running the React App
Next we'll open our editor. You can use any editor of your choice. So I'm going to use an editor called Visual Studio code and let's open up the terminal here. And I also have the command prompt open where I've navigated to a folder that I've created called react.js demos. Now we'll invoke the npm package manager which is invoked by the command npx. So npx will not only install packages but also execute them once they are installed. So once they are downloaded it will execute the package and we will use npx to go and create a react application called client. So while we give it time for the installation to complete, we can then open it within our editor. So we'll give it time so that the installation completes. So the installation is completed, and so we've seen here that the installation is now completed.
Launching the React Development Server
Let's go and open up this project. So I will say file and open folder and let me pick up that folder and we will open this application called client. So that's my client app. Let's fire up the terminal. Okay so that has launched the terminal for us. And here all we need to do to fire up this application and get it running is npm start, which will compile and start up this application that is created. Let's close this. We'll go to the browser and now let's say localhost 3000. So that gives us a startup page, the sample default startup page for the first client application and this is going to work as a client.
Creating the Node.js Express API Server
We'll now go and try to create the back end application which is going to be another application that we will set up. And to create that, let's say npx express generator api. Okay so this will create an express application on node.js called api and let's give it some time for installation. Okay so that's done. Clear this screen. We'll come out here, we'll open another instance of the editor. We'll say open folder and that's the api application. We'll say select folder and the api application is opened. Let's go to the terminal. Now in the terminal we will attempt to install all of the packages that are required that would be logged in the package.json file. So the package.json file here would be listed, so you can see we have a list of packages that it uses and npm install will go and install all of these packages that were pre-listed here. So let me ensure it's executed correctly and we'll fire that once more. That's done. So npm install has installed all of the packages required. And let me terminate this run by pressing a control c so this terminates the client application that was executing and now we will say npm start so that this application executes. And let's refresh. So that's the standard express application now that has got installed.
Configuring the API Port and Creating a New Route
Now let's go to the api application, we'll go into the bin folder and here we'll have a file called www. We will change the default port number from 3000 to 9000. Let me stop this application from executing. We've just updated the port number. Now let's go to the routes and we'll create a new file in the routes folder called test api dot js. Here we will say variable express equal to require express and here we'll say variable router equal to express dot router. And here we will say router dot get. We'll open this, so that's the default route, root route is going to be slash for which we'll add a callback function which will take the request and the response parameter and next pointer in case there is another function to call post that. And here we will just send a simple message saying api is working okay, a simple message sent out for the root default route. And we'll have to export this so we'll say module dot exports equal to router. All right so that's done.
Registering and Testing the New API Endpoint
Let's go to the app.js file and here let us import that. So here is where we will import this by saying app.use, we want to use the test api file and that is test api router. And this is exactly the same variable name that we will declare here which will be equal to require and we are going to say routes test api. All right so let's try launching this now. We would say npm start after adding this code. Let's go out here and 3000 test api is going to be the url to hit. It's not 3000 but 9000 now because we just updated the port so 9000 test api and there we have a message which says that the api is working properly. So this is tested now.
Connecting React to the API with Fetch
Let's go to the client application. In the client application let's go to the app.js file. Okay this is the file that we would have to revamp a bit. So let's revamp this. Here we will declare a class app which extends, so that creates a new module, so it extends react.component. And here we have constructor, we will accept the props. Here I would pass props to the super class constructor and set the state to api response. Currently it just has an empty value.
Next we'll add up a new function called call api which will generate a call to that api url which was http localhost 9000 was the port and test api was the url. Once this is called we will then call the then function, declare response, generate a call to response dot text. And then we will again say this dot set state api response is going to be equal to the response that comes in from that url which is nothing but a string which says api is working.
Another function called component will mount. So the moment the component is initialized on the screen and loaded we will generate a call to this function we created called call api. Then comes the render function. In the render function we would go and return a div class name as app. This would be app header, the standard logo after which in the paragraph, we wouldn't need the link here. Right after the header we'll add a paragraph where we will print this dot state and the variable we created called api response and we will data bind to that. So that largely completes uh the return. So we simply create this application, uh that's the react application that will talk to this api that is and this uh url that is hosted on node, communicate with it, get a simple string as a response, print that string inside this react application.
Implementing CORS on the API Server
So once that's done uh we have the componentWillMount which is a life cycle method here. It's a lifecycle event that gets triggered the moment the component loads and that's when we have actually gone and executed the call api custom function.
Let's go to the api application. We'll terminate the execution here. There's one more step that we'll have to perform which is cross origin resource sharing which means that to allow the react application to communicate from another hosted domain to this particular domain server, we will actually have to enable cross origin scripting and sharing otherwise it will block the request coming from another application. So for that we'll have to install globally cross origin module and save indicates that it's going to do a global install for all applications that are on this particular system. So we've installed this and we'll clear the screen. Let's go to the app.js and right here is where we would want it to go and use CORS. So we will say app.use(cors) so that it uses this particular api. And here is where we will declare the course variable and go and import the new library package that we just installed which is cors. So looks good and now let's fire up this application with an npm start. Let's also fire up client with an npm start.
Final Demonstration and Conclusion
And now when I go and try looking for localhost 3000 which is the react application, the react application should go and talk to the api that is hosted on node.js which returns to me that string message. So if I go and ping that api separately which is localhost 9000 test api, you can see this is a standard message. So here I directly pinged the api that's hosted in node.js. Now we are consuming it through the react.js application and if you scroll down you can see the message returned from node.js into react saying the api is working properly.
So the practical impact of this is to actually host restful services etc on node as a server and you can go and consume the data that is returned. There could be in string text or json format directly into the react.js acting as a client application. Finally we'd like to extend a big thank you for viewing our content and I hope this has added value to your learning journey and has been instrumental in supporting you and assisting you with learning the right skills and acquiring the right skills on this technology to help extend and grow your career path and your journey way forward in the industry. Thank you so much and a big thank you on behalf of the Simplilearn platform.
Outro
Hi there. If you like this video, subscribe to the Simply Learn YouTube channel and click here to watch similar videos. To nerd up and get certified, click here.